INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Interpolate inline globbing groups. | def InterpolateGrouping(self, pattern):
"""Interpolate inline globbing groups."""
components = []
offset = 0
for match in GROUPING_PATTERN.finditer(pattern):
components.append([pattern[offset:match.start()]])
# Expand the attribute into the set of possibilities:
alternatives = match.g... |
Return the current glob as a simple regex. | def AsRegEx(self):
"""Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object.
"""
parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value)
result = u"".join(self._ReplaceRegExPart(p) for p in parts)
return rdf_stand... |
Add a value to a date. | def dateadd(value: fields.DateTime(),
addend: fields.Int(validate=Range(min=1)),
unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'):
"""Add a value to a date."""
value = value or dt.datetime.utcnow()
if unit == 'minutes':
delta = dt.timedelta(minutes=addend)
el... |
Returns the name of all arguments a function takes | def arguments(function, extra_arguments=0):
"""Returns the name of all arguments a function takes"""
if not hasattr(function, '__code__'):
return ()
return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments] |
Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that s compatible with the supplied function | def generate_accepted_kwargs(function, *named_arguments):
"""Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's
compatible with the supplied function
"""
if hasattr(function, '__code__') and takes_kwargs(function):
function_takes_kwargs = ... |
Wraps authentication logic verify_user through to the authentication function. | def authenticator(function, challenges=()):
"""Wraps authentication logic, verify_user through to the authentication function.
The verify_user function passed in should accept an API key and return a user object to
store in the request context if authentication succeeded.
"""
challenges = challenge... |
Basic HTTP Authentication | def basic(request, response, verify_user, realm='simple', context=None, **kwargs):
"""Basic HTTP Authentication"""
http_auth = request.auth
response.set_header('WWW-Authenticate', 'Basic')
if http_auth is None:
return
if isinstance(http_auth, bytes):
http_auth = http_auth.decode('ut... |
API Key Header Authentication | def api_key(request, response, verify_user, context=None, **kwargs):
"""API Key Header Authentication
The verify_user function passed in to ths authenticator shall receive an
API key as input, and return a user object to store in the request context
if the request was successful.
"""
api_key = ... |
Token verification | def token(request, response, verify_user, context=None, **kwargs):
"""Token verification
Checks for the Authorization header and verifies using the verify_user function
"""
token = request.get_header('Authorization')
if token:
try:
verified_token = verify_user(token)
exc... |
Returns a simple verification callback that simply verifies that the users and password match that provided | def verify(user, password):
"""Returns a simple verification callback that simply verifies that the users and password match that provided"""
def verify_user(user_name, user_password):
if user_name == user and user_password == password:
return user_name
return False
return verify... |
Get session ID from cookie load corresponding session data from coupled store and inject session data into the request context. | def process_request(self, request, response):
"""Get session ID from cookie, load corresponding session data from coupled store and inject session data into
the request context.
"""
sid = request.cookies.get(self.cookie_name, None)
data = {}
if sid is not None:
... |
Save request context in coupled store object. Set cookie containing a session ID. | def process_response(self, request, response, resource, req_succeeded):
"""Save request context in coupled store object. Set cookie containing a session ID."""
sid = request.cookies.get(self.cookie_name, None)
if sid is None or not self.store.exists(sid):
sid = self.generate_sid()
... |
Given a request/ response pair generate a logging format similar to the NGINX combined style. | def _generate_combined_log(self, request, response):
"""Given a request/response pair, generate a logging format similar to the NGINX combined style."""
current_time = datetime.utcnow()
data_len = '-' if response.data is None else len(response.data)
return '{0} - - [{1}] {2} {3} {4} {5} ... |
Logs the basic endpoint requested | def process_request(self, request, response):
"""Logs the basic endpoint requested"""
self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type)) |
Logs the basic data returned by the API | def process_response(self, request, response, resource, req_succeeded):
"""Logs the basic data returned by the API"""
self.logger.info(self._generate_combined_log(request, response)) |
Match a request with parameter to it s corresponding route | def match_route(self, reqpath):
"""Match a request with parameter to it's corresponding route"""
route_dicts = [routes for _, routes in self.api.http.routes.items()][0]
routes = [route for route, _ in route_dicts.items()]
if reqpath not in routes:
for route in routes: # repl... |
Add CORS headers to the response | def process_response(self, request, response, resource, req_succeeded):
"""Add CORS headers to the response"""
response.set_header('Access-Control-Allow-Credentials', str(self.allow_credentials).lower())
origin = request.get_header('ORIGIN')
if origin and (origin in self.allow_origins) ... |
Creates a new type handler with the specified type - casting handler | def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True,
accept_context=False):
"""Creates a new type handler with the specified type-casting handler"""
extend = extend if type(extend) == type else type(extend)
def new_type_handler(functio... |
Allows quick wrapping of any Python type cast function for use as a hug type annotation | def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False):
"""Allows quick wrapping of any Python type cast function for use as a hug type annotation"""
return create(
doc,
error_text,
exception_handlers=exception_handlers,
chain=False,
... |
Redirects to the specified location using the provided http_code ( defaults to HTTP_302 FOUND ) | def to(location, code=falcon.HTTP_302):
"""Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)"""
raise falcon.http_status.HTTPStatus(code, {'location': location}) |
Converts text that may be camelcased into an underscored format | def underscore(text):
"""Converts text that may be camelcased into an underscored format"""
return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower() |
Hug API Development Server | def hug(file: 'A Python file that contains a Hug API'=None, module: 'A Python module that contains a Hug API'=None,
host: 'Interface to bind to'='', port: number=8000, no_404_documentation: boolean=False,
manual_reload: boolean=False, interval: number=1,
command: 'Run a command defined in the gi... |
Authenticate and return a token | def token_gen_call(username, password):
"""Authenticate and return a token"""
secret_key = 'super-secret-key-please-change'
mockusername = 'User2'
mockpassword = 'Mypassword'
if mockpassword == password and mockusername == username: # This is an example. Don't do that.
return {"token" : jwt.... |
returns documentation for the current api | def documentation(default=None, api_version=None, api=None, **kwargs):
"""returns documentation for the current api"""
api_version = default or api_version
if api:
return api.http.documentation(base_url="", api_version=api_version) |
Takes JSON formatted data converting it into native Python objects | def json(body, charset='utf-8', **kwargs):
"""Takes JSON formatted data, converting it into native Python objects"""
return json_converter.loads(text(body, charset=charset)) |
Converts query strings into native Python objects | def urlencoded(body, charset='ascii', **kwargs):
"""Converts query strings into native Python objects"""
return parse_query_string(text(body, charset=charset), False) |
Converts multipart form data into native Python objects | def multipart(body, content_length=0, **header_params):
"""Converts multipart form data into native Python objects"""
header_params.setdefault('CONTENT-LENGTH', content_length)
if header_params and 'boundary' in header_params:
if type(header_params['boundary']) is str:
header_params['bou... |
Sets up and fills test directory for serving. | 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. | 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. | 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,
... |
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. | 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 | 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... |
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 ... |
Checks to see if all requirements set pass | 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. | 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: | 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: | 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: | 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: | 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. | 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.