_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q240800
ErrorReturn.as_error
train
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
python
{ "resource": "" }
q240801
Connection.release_name_async
train
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) : "releases a registered bus name." assert self.loop != None, "no event loop to attach coroutine to" return \ await self.connection.bus_release_name_async(bus_name, error = error, timeout =...
python
{ "resource": "" }
q240802
DefaultAdapter
train
def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_l...
python
{ "resource": "" }
q240803
ListAdapters
train
def ListAdapters(self): '''List all known adapters ''' adapters = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: adapters.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(adapters, variant_level=1)
python
{ "resource": "" }
q240804
CreateDevice
train
def CreateDevice(self, device_address): '''Create a new device ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = self.path path = adapter_path + '/' + device_name if path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Could not ...
python
{ "resource": "" }
q240805
AddDevice
train
def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself...
python
{ "resource": "" }
q240806
ListDevices
train
def ListDevices(self): '''List all known devices ''' devices = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: devices.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(devices, variant_level=1)
python
{ "resource": "" }
q240807
FindDevice
train
def FindDevice(self, address): '''Find a specific device by bluetooth address. ''' for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: o = mockobject.objects[obj] if o.props[DEVICE_IFACE]['Address'] \ == dbus.String(ad...
python
{ "resource": "" }
q240808
Connect
train
def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] dev...
python
{ "resource": "" }
q240809
Disconnect
train
def Disconnect(self): '''Disconnect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] ...
python
{ "resource": "" }
q240810
AddEthernetDevice
train
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values pleas...
python
{ "resource": "" }
q240811
AddWiFiDevice
train
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit...
python
{ "resource": "" }
q240812
AddAccessPoint
train
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. ...
python
{ "resource": "" }
q240813
AddWiFiConnection
train
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access point...
python
{ "resource": "" }
q240814
AddActiveConnection
train
def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please no...
python
{ "resource": "" }
q240815
RemoveAccessPoint
train
def RemoveAccessPoint(self, dev_path, ap_path): '''Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) ap...
python
{ "resource": "" }
q240816
RemoveWifiConnection
train
def RemoveWifiConnection(self, dev_path, connection_path): '''Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_pat...
python
{ "resource": "" }
q240817
RemoveActiveConnection
train
def RemoveActiveConnection(self, dev_path, active_connection_path): '''Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ''' self.SetDeviceDisconne...
python
{ "resource": "" }
q240818
SettingsAddConnection
train
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'u...
python
{ "resource": "" }
q240819
ConnectionUpdate
train
def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MA...
python
{ "resource": "" }
q240820
ConnectionDelete
train
def ConnectionDelete(self): '''Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If...
python
{ "resource": "" }
q240821
AddAC
train
def AddAC(self, device_name, model_name): '''Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Retu...
python
{ "resource": "" }
q240822
AddDischargingBattery
train
def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): '''Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seco...
python
{ "resource": "" }
q240823
SetupDisplayDevice
train
def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): '''Convenience method to configure DisplayDevice properties This calls Set() for all properties that the Disp...
python
{ "resource": "" }
q240824
SetDeviceProperties
train
def SetDeviceProperties(self, object_path, properties): '''Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; ...
python
{ "resource": "" }
q240825
AddSeat
train
def AddSeat(self, seat): '''Convenience method to add a seat. Return the object path of the new seat. ''' seat_path = '/org/freedesktop/login1/seat/' + seat if seat_path in mockobject.objects: raise dbus.exceptions.DBusException('Seat %s already exists' % seat, ...
python
{ "resource": "" }
q240826
AddUser
train
def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, ...
python
{ "resource": "" }
q240827
AddSession
train
def AddSession(self, session_id, seat, uid, username, active): '''Convenience method to add a session. If the given seat and/or user do not exit, they will be created. Return the object path of the new session. ''' seat_path = dbus.ObjectPath('/org/freedesktop/login1/seat/' + seat) if seat_pat...
python
{ "resource": "" }
q240828
DBusMockObject._set_up_object_manager
train
def _set_up_object_manager(self): '''Set up this mock object as a D-Bus ObjectManager.''' if self.path == '/': cond = 'k != \'/\'' else: cond = 'k.startswith(\'%s/\')' % self.path self.AddMethod(OBJECT_MANAGER_IFACE, 'GetManagedObjects', ''...
python
{ "resource": "" }
q240829
DBusMockObject.Get
train
def Get(self, interface_name, property_name): '''Standard D-Bus API for getting a property value''' self.log('Get %s.%s' % (interface_name, property_name)) if not interface_name: interface_name = self.interface try: return self.GetAll(interface_name)[property_na...
python
{ "resource": "" }
q240830
DBusMockObject.GetAll
train
def GetAll(self, interface_name, *args, **kwargs): '''Standard D-Bus API for getting all property values''' self.log('GetAll ' + interface_name) if not interface_name: interface_name = self.interface try: return self.props[interface_name] except KeyError...
python
{ "resource": "" }
q240831
DBusMockObject.Set
train
def Set(self, interface_name, property_name, value, *args, **kwargs): '''Standard D-Bus API for setting a property value''' self.log('Set %s.%s%s' % (interface_name, property_name, self.format_args((value,)))) try: ...
python
{ "resource": "" }
q240832
DBusMockObject.AddObject
train
def AddObject(self, path, interface, properties, methods): '''Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value m...
python
{ "resource": "" }
q240833
DBusMockObject.RemoveObject
train
def RemoveObject(self, path): '''Remove a D-Bus object from the mock As with AddObject, this will *not* emit the InterfacesRemoved signal if it’s an ObjectManager instance. ''' try: objects[path].remove_from_connection() del objects[path] except K...
python
{ "resource": "" }
q240834
DBusMockObject.Reset
train
def Reset(self): '''Reset the mock object state. Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemp...
python
{ "resource": "" }
q240835
DBusMockObject.AddMethod
train
def AddMethod(self, interface, name, in_sig, out_sig, code): '''Add a method to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). n...
python
{ "resource": "" }
q240836
DBusMockObject.AddMethods
train
def AddMethods(self, interface, methods): '''Add several methods to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). methods: list...
python
{ "resource": "" }
q240837
DBusMockObject.AddProperty
train
def AddProperty(self, interface, name, value): '''Add property to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). name: Propert...
python
{ "resource": "" }
q240838
DBusMockObject.AddProperties
train
def AddProperties(self, interface, properties): '''Add several properties to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). pr...
python
{ "resource": "" }
q240839
DBusMockObject.AddTemplate
train
def AddTemplate(self, template, parameters): '''Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular ...
python
{ "resource": "" }
q240840
DBusMockObject.EmitSignal
train
def EmitSignal(self, interface, name, signature, args): '''Emit a signal from the object. interface: D-Bus interface to send the signal from. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). ...
python
{ "resource": "" }
q240841
DBusMockObject.GetMethodCalls
train
def GetMethodCalls(self, method): '''List all the logged calls of a particular method. Return a list of (timestamp, args_list) tuples. ''' return [(row[0], row[2]) for row in self.call_log if row[1] == method]
python
{ "resource": "" }
q240842
DBusMockObject.mock_method
train
def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs): '''Master mock method. This gets "instantiated" in AddMethod(). Execute the code snippet of the method and return the "ret" variable if it was set. ''' # print('mock_method', dbus_method, self, in_sign...
python
{ "resource": "" }
q240843
DBusMockObject.format_args
train
def format_args(self, args): '''Format a D-Bus argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a...
python
{ "resource": "" }
q240844
DBusMockObject.log
train
def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile.fileno() else: fd = sys.stdout.fileno() ...
python
{ "resource": "" }
q240845
DBusMockObject.Introspect
train
def Introspect(self, object_path, connection): '''Return XML description of this object's interfaces, methods and signals. This wraps dbus-python's Introspect() method to include the dynamic methods and properties. ''' # temporarily add our dynamic methods cls = self.__c...
python
{ "resource": "" }
q240846
CreateSession
train
def CreateSession(self, destination, args): '''OBEX method to create a new transfer session. The destination must be the address of the destination Bluetooth device. The given arguments must be a map from well-known keys to values, containing at least the ‘Target’ key, whose value must be ‘PBAP’ (other...
python
{ "resource": "" }
q240847
RemoveSession
train
def RemoveSession(self, session_path): '''OBEX method to remove an existing transfer session. This takes the path of the transfer Session object and removes it. ''' manager = mockobject.objects['/'] # Remove all the session's transfers. transfer_id = 0 while session_path + '/transfer' + s...
python
{ "resource": "" }
q240848
PullAll
train
def PullAll(self, target_file, filters): '''OBEX method to start a pull transfer of a phone book. This doesn't complete the transfer; code to mock up activating and completing the transfer must be provided by the test driver, as it’s too complex and test-specific to put here. The target_file is th...
python
{ "resource": "" }
q240849
UpdateStatus
train
def UpdateStatus(self, is_complete): '''Mock method to update the transfer status. If is_complete is False, this marks the transfer is active; otherwise it marks the transfer as complete. It is an error to call this method after calling it with is_complete as True. In both cases, it updates the nu...
python
{ "resource": "" }
q240850
AddModem
train
def AddModem(self, name, properties): '''Convenience method to add a modem You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac". For future extensions you can specify a "properties" array, but no extra properties are supported for now. Returns the new obj...
python
{ "resource": "" }
q240851
add_voice_call_api
train
def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [...
python
{ "resource": "" }
q240852
add_netreg_api
train
def add_netreg_api(mock): '''Add org.ofono.NetworkRegistration API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperties('org.ofono.NetworkRegistration', { 'Mode': 'auto', 'Status': 'register...
python
{ "resource": "" }
q240853
add_simmanager_api
train
def add_simmanager_api(self, mock): '''Add org.ofono.SimManager API to a mock''' iface = 'org.ofono.SimManager' mock.AddProperties(iface, { 'BarredDialing': _parameters.get('BarredDialing', False), 'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)), 'FixedDialing':...
python
{ "resource": "" }
q240854
add_connectionmanager_api
train
def add_connectionmanager_api(mock): '''Add org.ofono.ConnectionManager API to a mock''' iface = 'org.ofono.ConnectionManager' mock.AddProperties(iface, { 'Attached': _parameters.get('Attached', True), 'Bearer': _parameters.get('Bearer', 'gprs'), 'RoamingAllowed': _parameters.get('R...
python
{ "resource": "" }
q240855
BlockDevice
train
def BlockDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as blocked. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This di...
python
{ "resource": "" }
q240856
ModelResource.create
train
def create(self, instance, errors): """ Create an instance of a model. :param instance: The created model instance. :param errors: Any errors. :return: The created model instance, or a dictionary of errors. """ if errors: return self.errors(errors) ...
python
{ "resource": "" }
q240857
ModelResource.patch
train
def patch(self, instance, errors): """ Partially update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) ...
python
{ "resource": "" }
q240858
ModelResource.put
train
def put(self, instance, errors): """ Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self...
python
{ "resource": "" }
q240859
ControllerBundle.before_init_app
train
def before_init_app(self, app: FlaskUnchained): """ Configure the Jinja environment and template loader. """ from .templates import (UnchainedJinjaEnvironment, UnchainedJinjaLoader) app.jinja_environment = UnchainedJinjaEnvironment app.jinj...
python
{ "resource": "" }
q240860
ControllerBundle.after_init_app
train
def after_init_app(self, app: FlaskUnchained): """ Configure an after request hook to set the ``csrf_token`` in the cookie. """ from flask_wtf.csrf import generate_csrf # send CSRF token in the cookie @app.after_request def set_csrf_cookie(response): ...
python
{ "resource": "" }
q240861
shell
train
def shell(): """ Runs a shell in the app context. If ``IPython`` is installed, it will be used, otherwise the default Python shell is used. """ ctx = _get_shell_ctx() try: import IPython IPython.embed(header=_get_shell_banner(), user_ns=ctx) except ImportError: import...
python
{ "resource": "" }
q240862
SecurityController.login
train
def login(self): """ View function to log a user in. Supports html and json requests. """ form = self._get_form('SECURITY_LOGIN_FORM') if form.validate_on_submit(): try: self.security_service.login_user(form.user, form.remember.data) except...
python
{ "resource": "" }
q240863
SecurityController.logout
train
def logout(self): """ View function to log a user out. Supports html and json requests. """ if current_user.is_authenticated: self.security_service.logout_user() if request.is_json: return '', HTTPStatus.NO_CONTENT self.flash(_('flask_unchained.b...
python
{ "resource": "" }
q240864
SecurityController.register
train
def register(self): """ View function to register user. Supports html and json requests. """ form = self._get_form('SECURITY_REGISTER_FORM') if form.validate_on_submit(): user = self.security_service.user_manager.create(**form.to_dict()) self.security_serv...
python
{ "resource": "" }
q240865
SecurityController.send_confirmation_email
train
def send_confirmation_email(self): """ View function which sends confirmation token and instructions to a user. """ form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM') if form.validate_on_submit(): self.security_service.send_email_confirmation_instructions(form.u...
python
{ "resource": "" }
q240866
SecurityController.confirm_email
train
def confirm_email(self, token): """ View function to confirm a user's token from the confirmation email send to them. Supports html and json requests. """ expired, invalid, user = \ self.security_utils_service.confirm_email_token_status(token) if not user or i...
python
{ "resource": "" }
q240867
SecurityController.forgot_password
train
def forgot_password(self): """ View function to request a password recovery email with a reset token. Supports html and json requests. """ form = self._get_form('SECURITY_FORGOT_PASSWORD_FORM') if form.validate_on_submit(): self.security_service.send_reset_pas...
python
{ "resource": "" }
q240868
SecurityController.reset_password
train
def reset_password(self, token): """ View function verify a users reset password token from the email we sent to them. It also handles the form for them to set a new password. Supports html and json requests. """ expired, invalid, user = \ self.security_utils_...
python
{ "resource": "" }
q240869
SecurityController.change_password
train
def change_password(self): """ View function for a user to change their password. Supports html and json requests. """ form = self._get_form('SECURITY_CHANGE_PASSWORD_FORM') if form.validate_on_submit(): self.security_service.change_password( c...
python
{ "resource": "" }
q240870
Security._get_pwd_context
train
def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext: """ Get the password hashing context. """ pw_hash = app.config.SECURITY_PASSWORD_HASH schemes = app.config.SECURITY_PASSWORD_SCHEMES if pw_hash not in schemes: allowed = (', '.join(schemes[:-1]) ...
python
{ "resource": "" }
q240871
Security._get_serializer
train
def _get_serializer(self, app: FlaskUnchained, name: str) -> URLSafeTimedSerializer: """ Get a URLSafeTimedSerializer for the given serialization context name. :param app: the :class:`FlaskUnchained` instance :param name: Serialization context. One of ``confirm``, ``login``, `...
python
{ "resource": "" }
q240872
Security._request_loader
train
def _request_loader(self, request: Request) -> Union[User, AnonymousUser]: """ Attempt to load the user from the request token. """ header_key = self.token_authentication_header args_key = self.token_authentication_key token = request.args.get(args_key, request.headers.ge...
python
{ "resource": "" }
q240873
bundles
train
def bundles(ctx): """ List discovered bundles. """ bundles = _get_bundles(ctx.obj.data['env']) print_table(('Name', 'Location'), [(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}') for bundle in bundles])
python
{ "resource": "" }
q240874
argument
train
def argument(*param_decls, cls=None, **attrs): """ Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. :param param_decls: the parameter declarations for this option or ...
python
{ "resource": "" }
q240875
option
train
def option(*param_decls, cls=None, **attrs): """ Options are usually optional values on the command line and have some extra features that arguments don't have. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument ...
python
{ "resource": "" }
q240876
APISpec._openapi_json
train
def _openapi_json(self): """Serve JSON spec file""" # We don't use Flask.jsonify here as it would sort the keys # alphabetically while we want to preserve the order. from pprint import pprint pprint(self.to_dict()) return current_app.response_class(json.dumps(self.to_dict...
python
{ "resource": "" }
q240877
APISpec._openapi_redoc
train
def _openapi_redoc(self): """ Expose OpenAPI spec with ReDoc The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL`` """ return render_template('openapi/redoc.html', title=self.app.config.API_TITLE or self.app.name, ...
python
{ "resource": "" }
q240878
APISpec.register_converter
train
def register_converter(self, converter, conv_type, conv_format=None): """ Register custom path parameter converter :param BaseConverter converter: Converter. Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter f...
python
{ "resource": "" }
q240879
list_loader
train
def list_loader(*decorator_args, model): """ Decorator to automatically query the database for all records of a model. :param model: The model class to query """ def wrapped(fn): @wraps(fn) def decorated(*args, **kwargs): return fn(model.query.all()) return decor...
python
{ "resource": "" }
q240880
post_loader
train
def post_loader(*decorator_args, serializer): """ Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request """ def wrapped(fn): @wraps(fn) def decorated(*args, **kwargs): return fn(*...
python
{ "resource": "" }
q240881
reset_command
train
def reset_command(force): """Drop database tables and run migrations.""" if not force: exit('Cancelled.') click.echo('Dropping DB tables.') drop_all() click.echo('Running DB migrations.') alembic.upgrade(migrate.get_config(None), 'head') click.echo('Done.')
python
{ "resource": "" }
q240882
YamlIncludeConstructor.load
train
def load(self, loader, pathname, recursive=False, encoding=None): """Once add the constructor to PyYAML loader class, Loader will use this function to include other YAML fils on parsing ``"!include"`` tag :param loader: Instance of PyYAML's loader class :param str pathname: path...
python
{ "resource": "" }
q240883
YamlIncludeConstructor.add_to_loader_class
train
def add_to_loader_class(cls, loader_class=None, tag=None, **kwargs): # type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor """ Create an instance of the constructor, and add it to the YAML `Loader` class :param loader_class: The `Loader` class add constructor to. ...
python
{ "resource": "" }
q240884
print_table
train
def print_table(column_names: IterableOfStrings, rows: IterableOfTuples, column_alignments: Optional[IterableOfStrings] = None, primary_column_idx: int = 0, ) -> None: """ Prints a table of information to the console. Automatically determines if th...
python
{ "resource": "" }
q240885
Connection.send
train
def send(self, message, envelope_from=None): """Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command. """ assert message.send_to, "No recipients have been added" assert message.sender, ( ...
python
{ "resource": "" }
q240886
_MailMixin.connect
train
def connect(self): """ Opens a connection to the mail host. """ app = getattr(self, "app", None) or current_app try: return Connection(app.extensions['mail']) except KeyError: raise RuntimeError("The curent application was" ...
python
{ "resource": "" }
q240887
Mail.init_app
train
def init_app(self, app): """Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance """ state = self.init_mail(app.config, app.debug, app.testin...
python
{ "resource": "" }
q240888
_DeferredBundleFunctions.url_defaults
train
def url_defaults(self, fn): """ Callback function for URL defaults for this bundle. It's called with the endpoint and values and should update the values passed in place. """ self._defer(lambda bp: bp.url_defaults(fn)) return fn
python
{ "resource": "" }
q240889
_DeferredBundleFunctions.url_value_preprocessor
train
def url_value_preprocessor(self, fn): """ Registers a function as URL value preprocessor for this bundle. It's called before the view functions are called and can modify the url values provided. """ self._defer(lambda bp: bp.url_value_preprocessor(fn)) return fn
python
{ "resource": "" }
q240890
_DeferredBundleFunctions.errorhandler
train
def errorhandler(self, code_or_exception): """ Registers an error handler that becomes active for this bundle only. Please be aware that routing does not happen local to a bundle so an error handler for 404 usually is not handled by a bundle unless it is caused inside a view fun...
python
{ "resource": "" }
q240891
controller
train
def controller(url_prefix_or_controller_cls: Union[str, Type[Controller]], controller_cls: Optional[Type[Controller]] = None, *, rules: Optional[Iterable[Union[Route, RouteGenerator]]] = None, ) -> RouteGenerator: """ This function is used to register ...
python
{ "resource": "" }
q240892
Unchained.service
train
def service(self, name: str = None): """ Decorator to mark something as a service. """ if self._services_initialized: from warnings import warn warn('Services have already been initialized. Please register ' f'{name} sooner.') return l...
python
{ "resource": "" }
q240893
Unchained.register_service
train
def register_service(self, name: str, service: Any): """ Method to register a service. """ if not isinstance(service, type): if hasattr(service, '__class__'): _ensure_service_name(service.__class__, name) self.services[name] = service r...
python
{ "resource": "" }
q240894
Unchained.before_request
train
def before_request(self, fn): """ Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None va...
python
{ "resource": "" }
q240895
Unchained.before_first_request
train
def before_first_request(self, fn): """ Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. """ self._defer(lambda app: app.before_first_re...
python
{ "resource": "" }
q240896
Unchained.after_request
train
def after_request(self, fn): """ Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function mig...
python
{ "resource": "" }
q240897
Unchained.teardown_request
train
def teardown_request(self, fn): """ Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:: ...
python
{ "resource": "" }
q240898
Unchained.teardown_appcontext
train
def teardown_appcontext(self, fn): """ Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ...
python
{ "resource": "" }
q240899
Unchained.context_processor
train
def context_processor(self, fn): """ Registers a template context processor function. """ self._defer(lambda app: app.context_processor(fn)) return fn
python
{ "resource": "" }