INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Sets up and fills test directory for serving.
Using different filetypes to see how they are dealt with.
The tempoary directory will clean itself up. | def setup(api=None):
"""Sets up and fills test directory for serving.
Using different filetypes to see how they are dealt with.
The tempoary directory will clean itself up.
"""
global tmp_dir_object
tmp_dir_object = tempfile.TemporaryDirectory()
dir_name = tmp_dir_object.name
dir_a =... |
Returns a different transformer depending on the content type passed in.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[content-type]': transformation_action,
...
} | def content_type(transformers, default=None):
"""Returns a different transformer depending on the content type passed in.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[content-type]': transformation_action,
... |
Returns a different transformer depending on the suffix at the end of the requested URL.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[suffix]': transformation_action,
...
} | def suffix(transformers, default=None):
"""Returns a different transformer depending on the suffix at the end of the requested URL.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[suffix]': transformation_action,
... |
Runs all set type transformers / validators against the provided input parameters and returns any errors | def validate(self, input_parameters, context):
"""Runs all set type transformers / validators against the provided input parameters and returns any errors"""
errors = {}
for key, type_handler in self.input_transformations.items():
if self.raise_on_invalid:
if key in ... |
Returns a different transformer depending on the prefix at the end of the requested URL.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[prefix]': transformation_action,
...
} | def prefix(transformers, default=None):
"""Returns a different transformer depending on the prefix at the end of the requested URL.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[prefix]': transformation_action,
... |
Returns the results of applying all passed in transformers to data
should pass in list of transformers
[transformer_1, transformer_2...] | def all(*transformers):
"""Returns the results of applying all passed in transformers to data
should pass in list of transformers
[transformer_1, transformer_2...]
"""
transformers = tuple(auto_kwargs(transformer) for transformer in transformers)
def transform(data, request=None, r... |
Checks to see if all requirements set pass
if all requirements pass nothing will be returned
otherwise, the error reported will be returned | def check_requirements(self, request=None, response=None, context=None):
"""Checks to see if all requirements set pass
if all requirements pass nothing will be returned
otherwise, the error reported will be returned
"""
for requirement in self.requires:
conclus... |
Produces general documentation for the interface | def documentation(self, add_to=None):
"""Produces general documentation for the interface"""
doc = OrderedDict if add_to is None else add_to
usage = self.interface.spec.__doc__
if usage:
doc['usage'] = usage
if getattr(self, 'requires', None):
doc['requir... |
Outputs the provided data using the transformations and output format specified for this CLI endpoint | def output(self, data, context):
"""Outputs the provided data using the transformations and output format specified for this CLI endpoint"""
if self.transform:
if hasattr(self.transform, 'context'):
self.transform.context = context
data = self.transform(data)
... |
Gathers and returns all parameters that will be used for this endpoint | def gather_parameters(self, request, response, context, api_version=None, **input_parameters):
"""Gathers and returns all parameters that will be used for this endpoint"""
input_parameters.update(request.params)
if self.parse_body and request.content_length:
body = request.stream
... |
Runs the transforms specified on this endpoint with the provided data, returning the data modified | def transform_data(self, data, request=None, response=None, context=None):
transform = self.transform
if hasattr(transform, 'context'):
self.transform.context = context
"""Runs the transforms specified on this endpoint with the provided data, returning the data modified"""
if... |
Returns the content type that should be used by default for this endpoint | def content_type(self, request=None, response=None):
"""Returns the content type that should be used by default for this endpoint"""
if callable(self.outputs.content_type):
return self.outputs.content_type(request=request, response=response)
else:
return self.outputs.cont... |
Returns the content type that should be used by default on validation errors | def invalid_content_type(self, request=None, response=None):
"""Returns the content type that should be used by default on validation errors"""
if callable(self.invalid_outputs.content_type):
return self.invalid_outputs.content_type(request=request, response=response)
else:
... |
Sets up the response defaults that are defined in the URL route | def set_response_defaults(self, response, request=None):
"""Sets up the response defaults that are defined in the URL route"""
for header_name, header_value in self.response_headers:
response.set_header(header_name, header_value)
if self.set_status:
response.status = self... |
Returns the documentation specific to an HTTP interface | def documentation(self, add_to=None, version=None, prefix="", base_url="", url=""):
"""Returns the documentation specific to an HTTP interface"""
doc = OrderedDict() if add_to is None else add_to
usage = self.interface.spec.__doc__
if usage:
doc['usage'] = usage
for... |
Returns all URLS that are mapped to this interface | def urls(self, version=None):
"""Returns all URLS that are mapped to this interface"""
urls = []
for base_url, routes in self.api.http.routes.items():
for url, methods in routes.items():
for method, versions in methods.items():
for interface_versio... |
Returns the first matching URL found for the specified arguments | def url(self, version=None, **kwargs):
"""Returns the first matching URL found for the specified arguments"""
for url in self.urls(version):
if [key for key in kwargs.keys() if not '{' + key + '}' in url]:
continue
return url.format(**kwargs)
raise KeyEr... |
Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) | def greet(event: str):
"""Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) """
greetings = "Happy"
if event == "Christmas":
greetings = "Merry"
if event == "Kwanzaa":
greetings = "Joyous"
if event == "wishes":
greetings = "Warm"
... |
Returns command help document when no command is specified | def nagiosCommandHelp(**kwargs):
"""
Returns command help document when no command is specified
"""
with open(os.path.join(DIRECTORY, 'document.html')) as document:
return document.read() |
Securely hash a password using a provided salt
:param password:
:param salt:
:return: Hex encoded SHA512 hash of provided password | def hash_password(password, salt):
"""
Securely hash a password using a provided salt
:param password:
:param salt:
:return: Hex encoded SHA512 hash of provided password
"""
password = str(password).encode('utf-8')
salt = str(salt).encode('utf-8')
return hashlib.sha512(password + sal... |
Create a random API key for a user
:param username:
:return: Hex encoded SHA512 random string | def gen_api_key(username):
"""
Create a random API key for a user
:param username:
:return: Hex encoded SHA512 random string
"""
salt = str(os.urandom(64)).encode('utf-8')
return hash_password(username, salt) |
Authenticate a username and password against our database
:param username:
:param password:
:return: authenticated username | def authenticate_user(username, password):
"""
Authenticate a username and password against our database
:param username:
:param password:
:return: authenticated username
"""
user_model = Query()
user = db.get(user_model.username == username)
if not user:
logger.warning("Use... |
Authenticate an API key against our database
:param api_key:
:return: authenticated username | def authenticate_key(api_key):
"""
Authenticate an API key against our database
:param api_key:
:return: authenticated username
"""
user_model = Query()
user = db.search(user_model.api_key == api_key)[0]
if user:
return user['username']
return False |
CLI Parameter to add a user to the database
:param username:
:param password:
:return: JSON status output | def add_user(username, password):
"""
CLI Parameter to add a user to the database
:param username:
:param password:
:return: JSON status output
"""
user_model = Query()
if db.search(user_model.username == username):
return {
'error': 'User {0} already exists'.format(... |
Get Job details
:param authed_user:
:return: | def get_token(authed_user: hug.directives.user):
"""
Get Job details
:param authed_user:
:return:
"""
user_model = Query()
user = db.search(user_model.username == authed_user)[0]
if user:
out = {
'user': user['username'],
'api_key': user['api_key']
... |
accepts file uploads | def upload_file(body):
"""accepts file uploads"""
# <body> is a simple dictionary of {filename: b'content'}
print('body: ', body)
return {'filename': list(body.keys()).pop(), 'filesize': len(list(body.values()).pop())} |
Says happy birthday to a user | def happy_birthday(name: hug.types.text, age: hug.types.number, hug_timer=3):
"""Says happy birthday to a user"""
return {'message': 'Happy {0} Birthday {1}!'.format(age, name),
'took': float(hug_timer)} |
Registers the wrapped method as a JSON converter for the provided types.
NOTE: custom converters are always globally applied | def json_convert(*kinds):
"""Registers the wrapped method as a JSON converter for the provided types.
NOTE: custom converters are always globally applied
"""
def register_json_converter(function):
for kind in kinds:
json_converters[kind] = function
return function
return... |
JSON (Javascript Serialized Object Notation) | def json(content, request=None, response=None, ensure_ascii=False, **kwargs):
"""JSON (Javascript Serialized Object Notation)"""
if hasattr(content, 'read'):
return content
if isinstance(content, tuple) and getattr(content, '_fields', None):
content = {field: getattr(content, field) for fie... |
Renders as the specified content type only if no errors are found in the provided data object | def on_valid(valid_content_type, on_invalid=json):
"""Renders as the specified content type only if no errors are found in the provided data object"""
invalid_kwargs = introspect.generate_accepted_kwargs(on_invalid, 'request', 'response')
invalid_takes_response = introspect.takes_all_arguments(on_invalid, '... |
HTML (Hypertext Markup Language) | def html(content, **kwargs):
"""HTML (Hypertext Markup Language)"""
if hasattr(content, 'read'):
return content
elif hasattr(content, 'render'):
return content.render().encode('utf8')
return str(content).encode('utf8') |
Dynamically creates an image type handler for the specified image type | def image(image_format, doc=None):
"""Dynamically creates an image type handler for the specified image type"""
@on_valid('image/{0}'.format(image_format))
def image_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = st... |
Dynamically creates a video type handler for the specified video type | def video(video_type, video_mime, doc=None):
"""Dynamically creates a video type handler for the specified video type"""
@on_valid(video_mime)
def video_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
... |
A dynamically retrieved file | def file(data, response, **kwargs):
"""A dynamically retrieved file"""
if not data:
response.content_type = 'text/plain'
return ''
if hasattr(data, 'read'):
name, data = getattr(data, 'name', ''), data
elif os.path.isfile(data):
name, data = data, open(data, 'rb')
el... |
Returns a content in a different format based on the clients provided content type,
should pass in a dict with the following format:
{'[content-type]': action,
...
} | def on_content_type(handlers, default=None, error='The requested content type does not match any of those allowed'):
"""Returns a content in a different format based on the clients provided content type,
should pass in a dict with the following format:
{'[content-type]': action,
...... |
Separates out the quality score from the accepted content_type | def accept_quality(accept, default=1):
"""Separates out the quality score from the accepted content_type"""
quality = default
if accept and ";" in accept:
accept, rest = accept.split(";", 1)
accept_quality = RE_ACCEPT_QUALITY.search(rest)
if accept_quality:
quality = floa... |
Returns a content in a different format based on the clients defined accepted content type,
should pass in a dict with the following format:
{'[content-type]': action,
...
} | def accept(handlers, default=None, error='The requested content type does not match any of those allowed'):
"""Returns a content in a different format based on the clients defined accepted content type,
should pass in a dict with the following format:
{'[content-type]': action,
...
... |
Returns a content in a different format based on the suffix placed at the end of the URL route
should pass in a dict with the following format:
{'[suffix]': action,
...
} | def suffix(handlers, default=None, error='The requested suffix does not match any of those allowed'):
"""Returns a content in a different format based on the suffix placed at the end of the URL route
should pass in a dict with the following format:
{'[suffix]': action,
...
... |
Returns a content in a different format based on the prefix placed at the end of the URL route
should pass in a dict with the following format:
{'[prefix]': action,
...
} | def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'):
"""Returns a content in a different format based on the prefix placed at the end of the URL route
should pass in a dict with the following format:
{'[prefix]': action,
...
... |
Returns a list of items currently in the database | def show():
"""Returns a list of items currently in the database"""
items = list(collection.find())
# JSON conversion chokes on the _id objects, so we convert
# them to strings here
for i in items:
i['_id'] = str(i['_id'])
return items |
Inserts the given object as a new item in the database.
Returns the ID of the newly created item. | def new(name: hug.types.text, description: hug.types.text):
"""Inserts the given object as a new item in the database.
Returns the ID of the newly created item.
"""
item_doc = {'name': name, 'description': description}
collection.insert_one(item_doc)
return str(item_doc['_id']) |
Calls the service at the specified URL using the "CALL" method | def request(self, method, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
"""Calls the service at the specified URL using the "CALL" method"""
raise NotImplementedError("Concrete services must define the request method") |
Calls the service at the specified URL using the "OPTIONS" method | def options(self, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
"""Calls the service at the specified URL using the "OPTIONS" method"""
return self.request('OPTIONS', url=url, headers=headers, timeout=timeout, **params) |
Add socket options to set | def setsockopt(self, *sockopts):
"""Add socket options to set"""
if type(sockopts[0]) in (list, tuple):
for sock_opt in sockopts[0]:
level, option, value = sock_opt
self.connection.sockopts.add((level, option, value))
else:
level, option, v... |
Create/Connect socket, apply options | def _register_socket(self):
"""Create/Connect socket, apply options"""
_socket = socket.socket(*Socket.protocols[self.connection.proto])
_socket.settimeout(self.timeout)
# Reconfigure original socket options.
if self.connection.sockopts:
for sock_opt in self.connecti... |
TCP/Stream sender and receiver | def _stream_send_and_receive(self, _socket, message, *args, **kwargs):
"""TCP/Stream sender and receiver"""
data = BytesIO()
_socket_fd = _socket.makefile(mode='rwb', encoding='utf-8')
_socket_fd.write(message.encode('utf-8'))
_socket_fd.flush()
for received in _socket_... |
User Datagram Protocol sender and receiver | def _dgram_send_and_receive(self, _socket, message, buffer_size=4096, *args):
"""User Datagram Protocol sender and receiver"""
_socket.send(message.encode('utf-8'))
data, address = _socket.recvfrom(buffer_size)
return BytesIO(data) |
Populate connection pool, send message, return BytesIO, and cleanup | def request(self, message, timeout=False, *args, **kwargs):
"""Populate connection pool, send message, return BytesIO, and cleanup"""
if not self.connection_pool.full():
self.connection_pool.put(self._register_socket())
_socket = self.connection_pool.get()
# setting timeout... |
Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist. | def get(self, key):
"""Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist."""
try:
data = self._data[key]
except KeyError:
raise StoreKeyNotFound(key)
return data |
Returns the top post from the provided section | def top_post(section: hug.types.one_of(('news', 'newest', 'show'))='news'):
"""Returns the top post from the provided section"""
content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
text = content.decode('utf-8')
return text.split('<tr class=\'athing\'>')[1].split("<a href"... |
A decorator that allows you to override the default output format for an API | def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if ap... |
A decorator that allows you to override the default output format for an API | def default_input_format(content_type='application/json', apply_globally=False, api=None):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
... |
A decorator that registers a single hug directive | def directive(apply_globally=False, api=None):
"""A decorator that registers a single hug directive"""
def decorator(directive_method):
if apply_globally:
hug.defaults.directives[underscore(directive_method.__name__)] = directive_method
else:
apply_to_api = hug.API(api) i... |
A decorator that registers a single hug context factory | def context_factory(apply_globally=False, api=None):
"""A decorator that registers a single hug context factory"""
def decorator(context_factory_):
if apply_globally:
hug.defaults.context_factory = context_factory_
else:
apply_to_api = hug.API(api) if api else hug.api.fro... |
A decorator that registers a single hug delete context function | def delete_context(apply_globally=False, api=None):
"""A decorator that registers a single hug delete context function"""
def decorator(delete_context_):
if apply_globally:
hug.defaults.delete_context = delete_context_
else:
apply_to_api = hug.API(api) if api else hug.api... |
Runs the provided function on startup, passing in an instance of the api | def startup(api=None):
"""Runs the provided function on startup, passing in an instance of the api"""
def startup_wrapper(startup_function):
apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function)
apply_to_api.add_startup_handler(startup_function)
return startup_fun... |
Registers a middleware function that will be called on every request | def request_middleware(api=None):
"""Registers a middleware function that will be called on every request"""
def decorator(middleware_method):
apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)
class MiddlewareRouter(object):
__slots__ = ()
d... |
Registers a middleware function that will be called on every response | def response_middleware(api=None):
"""Registers a middleware function that will be called on every response"""
def decorator(middleware_method):
apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)
class MiddlewareRouter(object):
__slots__ = ()
... |
Registers a middleware function that will be called on every request and response | def reqresp_middleware(api=None):
"""Registers a middleware function that will be called on every request and response"""
def decorator(middleware_generator):
apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_generator)
class MiddlewareRouter(object):
__slots__ ... |
Registers a middleware class | def middleware_class(api=None):
"""Registers a middleware class"""
def decorator(middleware_class):
apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_class)
apply_to_api.http.add_middleware(middleware_class())
return middleware_class
return decorator |
Extends the current api, with handlers from an imported api. Optionally provide a route that prefixes access | def extend_api(route="", api=None, base_url="", **kwargs):
"""Extends the current api, with handlers from an imported api. Optionally provide a route that prefixes access"""
def decorator(extend_with):
apply_to_api = hug.API(api) if api else hug.api.from_object(extend_with)
for extended_api in e... |
Enables building decorators around functions used for hug routes without changing their function signature | def wraps(function):
"""Enables building decorators around functions used for hug routes without changing their function signature"""
def wrap(decorator):
decorator = functools.wraps(function)(decorator)
if not hasattr(function, 'original'):
decorator.original = function
else... |
Modifies the provided function to support kwargs by only passing along kwargs for parameters it accepts | def auto_kwargs(function):
"""Modifies the provided function to support kwargs by only passing along kwargs for parameters it accepts"""
supported = introspect.arguments(function)
@wraps(function)
def call_function(*args, **kwargs):
return function(*args, **{key: value for key, value in kwargs.... |
Get time from a locally running NTP server | def get_time():
"""Get time from a locally running NTP server"""
time_request = '\x1b' + 47 * '\0'
now = struct.unpack("!12I", ntp_service.request(time_request, timeout=5.0).data.read())[10]
return time.ctime(now - EPOCH_START) |
Simple reverse http proxy function that returns data/html from another http server (via sockets)
only drawback is the peername is static, and currently does not support being changed.
Example: curl localhost:8000/reverse_http_proxy?length=400 | def reverse_http_proxy(length: int=100):
"""Simple reverse http proxy function that returns data/html from another http server (via sockets)
only drawback is the peername is static, and currently does not support being changed.
Example: curl localhost:8000/reverse_http_proxy?length=400"""
http_request ... |
Validation only succeeds if all passed in validators return no errors | def all(*validators):
"""Validation only succeeds if all passed in validators return no errors"""
def validate_all(fields):
for validator in validators:
errors = validator(fields)
if errors:
return errors
validate_all.__doc__ = " and ".join(validator.__doc__ ... |
If any of the specified validators pass the validation succeeds | def any(*validators):
"""If any of the specified validators pass the validation succeeds"""
def validate_any(fields):
errors = {}
for validator in validators:
validation_errors = validator(fields)
if not validation_errors:
return
errors.update(... |
Enables ensuring that one of multiple optional fields is set | def contains_one_of(*fields):
"""Enables ensuring that one of multiple optional fields is set"""
message = 'Must contain any one of the following fields: {0}'.format(', '.join(fields))
def check_contains(endpoint_fields):
for field in fields:
if field in endpoint_fields:
... |
Adds additional requirements to the specified route | def requires(self, requirements, **overrides):
"""Adds additional requirements to the specified route"""
return self.where(requires=tuple(self.route.get('requires', ())) + tuple(requirements), **overrides) |
Removes individual requirements while keeping all other defined ones within a route | def doesnt_require(self, requirements, **overrides):
"""Removes individual requirements while keeping all other defined ones within a route"""
return self.where(requires=tuple(set(self.route.get('requires', ())).difference(requirements if
type(... |
Creates a new route, based on the current route, with the specified overrided values | def where(self, **overrides):
"""Creates a new route, based on the current route, with the specified overrided values"""
route_data = self.route.copy()
route_data.update(overrides)
return self.__class__(**route_data) |
Sets the route to raise validation errors instead of catching them | def raise_on_invalid(self, setting=True, **overrides):
"""Sets the route to raise validation errors instead of catching them"""
return self.where(raise_on_invalid=setting, **overrides) |
Tells hug to automatically parse the input body if it matches a registered input format | def parse_body(self, automatic=True, **overrides):
"""Tells hug to automatically parse the input body if it matches a registered input format"""
return self.where(parse_body=automatic, **overrides) |
Adds the specified response headers while keeping existing ones in-tact | def add_response_headers(self, headers, **overrides):
"""Adds the specified response headers while keeping existing ones in-tact"""
response_headers = self.route.get('response_headers', {}).copy()
response_headers.update(headers)
return self.where(response_headers=response_headers, **ove... |
Convenience method for quickly adding cache header to route | def cache(self, private=False, max_age=31536000, s_maxage=None, no_cache=False, no_store=False,
must_revalidate=False, **overrides):
"""Convenience method for quickly adding cache header to route"""
parts = ('private' if private else 'public', 'max-age={0}'.format(max_age),
... |
Convenience method for quickly allowing other resources to access this one | def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides):
"""Convenience method for quickly allowing other resources to access this one"""
response_headers = {}
if origins:
@hug.response_middleware()
def process_data(reque... |
Sets the acceptable HTTP method to a GET | def get(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to a GET"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='GET', **overrides) |
Sets the acceptable HTTP method to DELETE | def delete(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to DELETE"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='DELETE', **overrides) |
Sets the acceptable HTTP method to POST | def post(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to POST"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='POST', **overrides) |
Sets the acceptable HTTP method to PUT | def put(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to PUT"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='PUT', **overrides) |
Sets the acceptable HTTP method to TRACE | def trace(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to TRACE"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='TRACE', **overrides) |
Sets the acceptable HTTP method to PATCH | def patch(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to PATCH"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='PATCH', **overrides) |
Sets the acceptable HTTP method to OPTIONS | def options(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to OPTIONS"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='OPTIONS', **overrides) |
Sets the acceptable HTTP method to HEAD | def head(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to HEAD"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='HEAD', **overrides) |
Sets the acceptable HTTP method to CONNECT | def connect(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to CONNECT"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='CONNECT', **overrides) |
Creates routes from a class, where the class method names should line up to HTTP METHOD types | def http_methods(self, urls=None, **route_data):
"""Creates routes from a class, where the class method names should line up to HTTP METHOD types"""
def decorator(class_definition):
instance = class_definition
if isinstance(class_definition, type):
instance = clas... |
Registers a method on an Object as a CLI route | def cli(self, method):
"""Registers a method on an Object as a CLI route"""
routes = getattr(method, '_hug_cli_routes', [])
routes.append(self.route)
method._hug_cli_routes = routes
return method |
Starts the process of building a new HTTP route linked to this API instance | def http(self, *args, **kwargs):
"""Starts the process of building a new HTTP route linked to this API instance"""
kwargs['api'] = self.api
return http(*args, **kwargs) |
Defines the handler that should handle not found requests against this API | def not_found(self, *args, **kwargs):
"""Defines the handler that should handle not found requests against this API"""
kwargs['api'] = self.api
return not_found(*args, **kwargs) |
Define the routes to static files the API should expose | def static(self, *args, **kwargs):
"""Define the routes to static files the API should expose"""
kwargs['api'] = self.api
return static(*args, **kwargs) |
Define URL prefixes/handler matches where everything under the URL prefix should be handled | def sink(self, *args, **kwargs):
"""Define URL prefixes/handler matches where everything under the URL prefix should be handled"""
kwargs['api'] = self.api
return sink(*args, **kwargs) |
Defines how this API should handle the provided exceptions | def exception(self, *args, **kwargs):
"""Defines how this API should handle the provided exceptions"""
kwargs['api'] = self.api
return exception(*args, **kwargs) |
Defines a CLI function that should be routed by this API | def cli(self, *args, **kwargs):
"""Defines a CLI function that should be routed by this API"""
kwargs['api'] = self.api
return cli(*args, **kwargs) |
Registers a class based router to this API | def object(self, *args, **kwargs):
"""Registers a class based router to this API"""
kwargs['api'] = self.api
return Object(*args, **kwargs) |
Returns a generator of all URLs attached to this API | def urls(self):
"""Returns a generator of all URLs attached to this API"""
for base_url, mapping in self.routes.items():
for url, _ in mapping.items():
yield base_url + url |
Returns all registered handlers attached to this API | def handlers(self):
"""Returns all registered handlers attached to this API"""
used = []
for base_url, mapping in self.routes.items():
for url, methods in mapping.items():
for method, versions in methods.items():
for version, handler in versions.it... |
Returns the set input_format handler for the given content_type | def input_format(self, content_type):
"""Returns the set input_format handler for the given content_type"""
return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None)) |
Sets an input format handler for this Hug API, given the specified content_type | def set_input_format(self, content_type, handler):
"""Sets an input format handler for this Hug API, given the specified content_type"""
if getattr(self, '_input_format', None) is None:
self._input_format = {}
self._input_format[content_type] = handler |
Adds a middleware object used to process all incoming requests against the API | def add_middleware(self, middleware):
"""Adds a middleware object used to process all incoming requests against the API"""
if self.middleware is None:
self._middleware = []
self.middleware.append(middleware) |
Adds a error handler to the hug api | def add_exception_handler(self, exception_type, error_handler, versions=(None, )):
"""Adds a error handler to the hug api"""
versions = (versions, ) if not isinstance(versions, (tuple, list)) else versions
if not hasattr(self, '_exception_handlers'):
self._exception_handlers = {}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.