repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Scifabric/pbs
helpers.py
_delete_tasks
def _delete_tasks(config, task_id, limit=100, offset=0): """Delete tasks from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: response = config.pbclient.delete_task(task_id) check_api_error(response) return "Task.id = %s and its associated task_runs have been deleted" % task_id else: limit = limit offset = offset tasks = config.pbclient.get_tasks(project.id, limit, offset) while len(tasks) > 0: for t in tasks: response = config.pbclient.delete_task(t.id) check_api_error(response) offset += limit tasks = config.pbclient.get_tasks(project.id, limit, offset) return "All tasks and task_runs have been deleted" except exceptions.ConnectionError: return ("Connection Error! The server %s is not responding" % config.server) except (ProjectNotFound, TaskNotFound): raise
python
def _delete_tasks(config, task_id, limit=100, offset=0): """Delete tasks from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: response = config.pbclient.delete_task(task_id) check_api_error(response) return "Task.id = %s and its associated task_runs have been deleted" % task_id else: limit = limit offset = offset tasks = config.pbclient.get_tasks(project.id, limit, offset) while len(tasks) > 0: for t in tasks: response = config.pbclient.delete_task(t.id) check_api_error(response) offset += limit tasks = config.pbclient.get_tasks(project.id, limit, offset) return "All tasks and task_runs have been deleted" except exceptions.ConnectionError: return ("Connection Error! The server %s is not responding" % config.server) except (ProjectNotFound, TaskNotFound): raise
[ "def", "_delete_tasks", "(", "config", ",", "task_id", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "try", ":", "project", "=", "find_project_by_short_name", "(", "config", ".", "project", "[", "'short_name'", "]", ",", "config", ".", "pb...
Delete tasks from a project.
[ "Delete", "tasks", "from", "a", "project", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L281-L305
Scifabric/pbs
helpers.py
_update_tasks_redundancy
def _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0): """Update tasks redundancy from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: response = config.pbclient.find_tasks(project.id, id=task_id) check_api_error(response) task = response[0] task.n_answers = redundancy response = config.pbclient.update_task(task) check_api_error(response) msg = "Task.id = %s redundancy has been updated to %s" % (task_id, redundancy) return msg else: limit = limit offset = offset tasks = config.pbclient.get_tasks(project.id, limit, offset) with click.progressbar(tasks, label="Updating Tasks") as pgbar: while len(tasks) > 0: for t in pgbar: t.n_answers = redundancy response = config.pbclient.update_task(t) check_api_error(response) # Check if for the data we have to auto-throttle task update sleep, msg = enable_auto_throttling(config, tasks) # If auto-throttling enabled, sleep for sleep seconds if sleep: # pragma: no cover time.sleep(sleep) offset += limit tasks = config.pbclient.get_tasks(project.id, limit, offset) return "All tasks redundancy have been updated" except exceptions.ConnectionError: return ("Connection Error! The server %s is not responding" % config.server) except (ProjectNotFound, TaskNotFound): raise
python
def _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0): """Update tasks redundancy from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: response = config.pbclient.find_tasks(project.id, id=task_id) check_api_error(response) task = response[0] task.n_answers = redundancy response = config.pbclient.update_task(task) check_api_error(response) msg = "Task.id = %s redundancy has been updated to %s" % (task_id, redundancy) return msg else: limit = limit offset = offset tasks = config.pbclient.get_tasks(project.id, limit, offset) with click.progressbar(tasks, label="Updating Tasks") as pgbar: while len(tasks) > 0: for t in pgbar: t.n_answers = redundancy response = config.pbclient.update_task(t) check_api_error(response) # Check if for the data we have to auto-throttle task update sleep, msg = enable_auto_throttling(config, tasks) # If auto-throttling enabled, sleep for sleep seconds if sleep: # pragma: no cover time.sleep(sleep) offset += limit tasks = config.pbclient.get_tasks(project.id, limit, offset) return "All tasks redundancy have been updated" except exceptions.ConnectionError: return ("Connection Error! The server %s is not responding" % config.server) except (ProjectNotFound, TaskNotFound): raise
[ "def", "_update_tasks_redundancy", "(", "config", ",", "task_id", ",", "redundancy", ",", "limit", "=", "300", ",", "offset", "=", "0", ")", ":", "try", ":", "project", "=", "find_project_by_short_name", "(", "config", ".", "project", "[", "'short_name'", "]...
Update tasks redundancy from a project.
[ "Update", "tasks", "redundancy", "from", "a", "project", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L308-L345
Scifabric/pbs
helpers.py
find_project_by_short_name
def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to \ search in all the server.' error = 'Project Not Found' raise ProjectNotFound(msg, error) return response[0] except exceptions.ConnectionError: raise except ProjectNotFound: raise
python
def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to \ search in all the server.' error = 'Project Not Found' raise ProjectNotFound(msg, error) return response[0] except exceptions.ConnectionError: raise except ProjectNotFound: raise
[ "def", "find_project_by_short_name", "(", "short_name", ",", "pbclient", ",", "all", "=", "None", ")", ":", "try", ":", "response", "=", "pbclient", ".", "find_project", "(", "short_name", "=", "short_name", ",", "all", "=", "all", ")", "check_api_error", "(...
Return project by short_name.
[ "Return", "project", "by", "short_name", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L348-L362
Scifabric/pbs
helpers.py
check_api_error
def check_api_error(api_response): print(api_response) """Check if returned API response contains an error.""" if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200: print("Server response code: %s" % api_response['code']) print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response) if type(api_response) == dict and (api_response.get('status') == 'failed'): if 'ProgrammingError' in api_response.get('exception_cls'): raise DatabaseError(message='PyBossa database error.', error=api_response) if ('DBIntegrityError' in api_response.get('exception_cls') and 'project' in api_response.get('target')): msg = 'PyBossa project already exists.' raise ProjectAlreadyExists(message=msg, error=api_response) if 'project' in api_response.get('target'): raise ProjectNotFound(message='PyBossa Project not found', error=api_response) if 'task' in api_response.get('target'): raise TaskNotFound(message='PyBossa Task not found', error=api_response) else: print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response)
python
def check_api_error(api_response): print(api_response) """Check if returned API response contains an error.""" if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200: print("Server response code: %s" % api_response['code']) print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response) if type(api_response) == dict and (api_response.get('status') == 'failed'): if 'ProgrammingError' in api_response.get('exception_cls'): raise DatabaseError(message='PyBossa database error.', error=api_response) if ('DBIntegrityError' in api_response.get('exception_cls') and 'project' in api_response.get('target')): msg = 'PyBossa project already exists.' raise ProjectAlreadyExists(message=msg, error=api_response) if 'project' in api_response.get('target'): raise ProjectNotFound(message='PyBossa Project not found', error=api_response) if 'task' in api_response.get('target'): raise TaskNotFound(message='PyBossa Task not found', error=api_response) else: print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response)
[ "def", "check_api_error", "(", "api_response", ")", ":", "print", "(", "api_response", ")", "if", "type", "(", "api_response", ")", "==", "dict", "and", "'code'", "in", "api_response", "and", "api_response", "[", "'code'", "]", "<>", "200", ":", "print", "...
Check if returned API response contains an error.
[ "Check", "if", "returned", "API", "response", "contains", "an", "error", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L365-L388
Scifabric/pbs
helpers.py
format_error
def format_error(module, error): """Format the error for the given module.""" logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
python
def format_error(module, error): """Format the error for the given module.""" logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
[ "def", "format_error", "(", "module", ",", "error", ")", ":", "logging", ".", "error", "(", "module", ")", "# Beautify JSON error", "print", "error", ".", "message", "print", "json", ".", "dumps", "(", "error", ".", "error", ",", "sort_keys", "=", "True", ...
Format the error for the given module.
[ "Format", "the", "error", "for", "the", "given", "module", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L391-L397
Scifabric/pbs
helpers.py
create_task_info
def create_task_info(task): """Create task_info field.""" task_info = None if task.get('info'): task_info = task['info'] else: task_info = task return task_info
python
def create_task_info(task): """Create task_info field.""" task_info = None if task.get('info'): task_info = task['info'] else: task_info = task return task_info
[ "def", "create_task_info", "(", "task", ")", ":", "task_info", "=", "None", "if", "task", ".", "get", "(", "'info'", ")", ":", "task_info", "=", "task", "[", "'info'", "]", "else", ":", "task_info", "=", "task", "return", "task_info" ]
Create task_info field.
[ "Create", "task_info", "field", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L400-L407
Scifabric/pbs
helpers.py
create_helping_material_info
def create_helping_material_info(helping): """Create helping_material_info field.""" helping_info = None file_path = None if helping.get('info'): helping_info = helping['info'] else: helping_info = helping if helping_info.get('file_path'): file_path = helping_info.get('file_path') del helping_info['file_path'] return helping_info, file_path
python
def create_helping_material_info(helping): """Create helping_material_info field.""" helping_info = None file_path = None if helping.get('info'): helping_info = helping['info'] else: helping_info = helping if helping_info.get('file_path'): file_path = helping_info.get('file_path') del helping_info['file_path'] return helping_info, file_path
[ "def", "create_helping_material_info", "(", "helping", ")", ":", "helping_info", "=", "None", "file_path", "=", "None", "if", "helping", ".", "get", "(", "'info'", ")", ":", "helping_info", "=", "helping", "[", "'info'", "]", "else", ":", "helping_info", "="...
Create helping_material_info field.
[ "Create", "helping_material_info", "field", "." ]
train
https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L410-L421
wndhydrnt/python-oauth2
oauth2/store/redisdb.py
TokenStore.fetch_by_code
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.read(code) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
python
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.read(code) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
[ "def", "fetch_by_code", "(", "self", ",", "code", ")", ":", "code_data", "=", "self", ".", "read", "(", "code", ")", "if", "code_data", "is", "None", ":", "raise", "AuthCodeNotFound", "return", "AuthorizationCode", "(", "*", "*", "code_data", ")" ]
Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`.
[ "Returns", "data", "belonging", "to", "an", "authorization", "code", "from", "redis", "or", "None", "if", "no", "data", "was", "found", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/redisdb.py#L61-L74
wndhydrnt/python-oauth2
oauth2/store/redisdb.py
TokenStore.save_code
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """ self.write(authorization_code.code, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
python
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """ self.write(authorization_code.code, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
[ "def", "save_code", "(", "self", ",", "authorization_code", ")", ":", "self", ".", "write", "(", "authorization_code", ".", "code", ",", "{", "\"client_id\"", ":", "authorization_code", ".", "client_id", ",", "\"code\"", ":", "authorization_code", ".", "code", ...
Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`.
[ "Stores", "the", "data", "belonging", "to", "an", "authorization", "code", "token", "in", "redis", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/redisdb.py#L76-L90
wndhydrnt/python-oauth2
oauth2/store/redisdb.py
TokenStore.save_token
def save_token(self, access_token): """ Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`. """ self.write(access_token.token, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.write(unique_token_key, access_token.__dict__) if access_token.refresh_token is not None: self.write(access_token.refresh_token, access_token.__dict__)
python
def save_token(self, access_token): """ Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`. """ self.write(access_token.token, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.write(unique_token_key, access_token.__dict__) if access_token.refresh_token is not None: self.write(access_token.refresh_token, access_token.__dict__)
[ "def", "save_token", "(", "self", ",", "access_token", ")", ":", "self", ".", "write", "(", "access_token", ".", "token", ",", "access_token", ".", "__dict__", ")", "unique_token_key", "=", "self", ".", "_unique_token_key", "(", "access_token", ".", "client_id...
Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`.
[ "Stores", "the", "access", "token", "and", "additional", "data", "in", "redis", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/redisdb.py#L99-L114
wndhydrnt/python-oauth2
oauth2/store/redisdb.py
TokenStore.delete_refresh_token
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.delete(access_token.token)
python
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.delete(access_token.token)
[ "def", "delete_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "access_token", "=", "self", ".", "fetch_by_refresh_token", "(", "refresh_token", ")", "self", ".", "delete", "(", "access_token", ".", "token", ")" ]
Deletes a refresh token after use :param refresh_token: The refresh token to delete.
[ "Deletes", "a", "refresh", "token", "after", "use", ":", "param", "refresh_token", ":", "The", "refresh", "token", "to", "delete", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/redisdb.py#L116-L123
wndhydrnt/python-oauth2
oauth2/store/redisdb.py
ClientStore.add_client
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to. """ self.write(client_id, {"identifier": client_id, "secret": client_secret, "redirect_uris": redirect_uris, "authorized_grants": authorized_grants, "authorized_response_types": authorized_response_types}) return True
python
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to. """ self.write(client_id, {"identifier": client_id, "secret": client_secret, "redirect_uris": redirect_uris, "authorized_grants": authorized_grants, "authorized_response_types": authorized_response_types}) return True
[ "def", "add_client", "(", "self", ",", "client_id", ",", "client_secret", ",", "redirect_uris", ",", "authorized_grants", "=", "None", ",", "authorized_response_types", "=", "None", ")", ":", "self", ".", "write", "(", "client_id", ",", "{", "\"identifier\"", ...
Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to.
[ "Add", "a", "client", "app", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/redisdb.py#L149-L167
wndhydrnt/python-oauth2
oauth2/tokengenerator.py
TokenGenerator.create_access_token_data
def create_access_token_data(self, grant_type): """ Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` is larger than 0, a ``refresh_token`` will be generated too. :rtype: dict """ result = {"access_token": self.generate(), "token_type": "Bearer"} if self.expires_in.get(grant_type, 0) > 0: result["refresh_token"] = self.generate() result["expires_in"] = self.expires_in[grant_type] return result
python
def create_access_token_data(self, grant_type): """ Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` is larger than 0, a ``refresh_token`` will be generated too. :rtype: dict """ result = {"access_token": self.generate(), "token_type": "Bearer"} if self.expires_in.get(grant_type, 0) > 0: result["refresh_token"] = self.generate() result["expires_in"] = self.expires_in[grant_type] return result
[ "def", "create_access_token_data", "(", "self", ",", "grant_type", ")", ":", "result", "=", "{", "\"access_token\"", ":", "self", ".", "generate", "(", ")", ",", "\"token_type\"", ":", "\"Bearer\"", "}", "if", "self", ".", "expires_in", ".", "get", "(", "g...
Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` is larger than 0, a ``refresh_token`` will be generated too. :rtype: dict
[ "Create", "data", "needed", "by", "an", "access", "token", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/tokengenerator.py#L22-L41
wndhydrnt/python-oauth2
oauth2/tokengenerator.py
URandomTokenGenerator.generate
def generate(self): """ :return: A new token :rtype: str """ random_data = os.urandom(100) hash_gen = hashlib.new("sha512") hash_gen.update(random_data) return hash_gen.hexdigest()[:self.token_length]
python
def generate(self): """ :return: A new token :rtype: str """ random_data = os.urandom(100) hash_gen = hashlib.new("sha512") hash_gen.update(random_data) return hash_gen.hexdigest()[:self.token_length]
[ "def", "generate", "(", "self", ")", ":", "random_data", "=", "os", ".", "urandom", "(", "100", ")", "hash_gen", "=", "hashlib", ".", "new", "(", "\"sha512\"", ")", "hash_gen", ".", "update", "(", "random_data", ")", "return", "hash_gen", ".", "hexdigest...
:return: A new token :rtype: str
[ ":", "return", ":", "A", "new", "token", ":", "rtype", ":", "str" ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/tokengenerator.py#L60-L70
wndhydrnt/python-oauth2
docs/examples/resource_owner_grant.py
ClientApplication._display_token
def _display_token(self): """ Display token information or redirect to login prompt if none is available. """ if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( access_token=self.token["access_token"]), {"Content-Type": "text/html"})
python
def _display_token(self): """ Display token information or redirect to login prompt if none is available. """ if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( access_token=self.token["access_token"]), {"Content-Type": "text/html"})
[ "def", "_display_token", "(", "self", ")", ":", "if", "self", ".", "token", "is", "None", ":", "return", "\"301 Moved\"", ",", "\"\"", ",", "{", "\"Location\"", ":", "\"/login\"", "}", "return", "(", "\"200 OK\"", ",", "self", ".", "TOKEN_TEMPLATE", ".", ...
Display token information or redirect to login prompt if none is available.
[ "Display", "token", "information", "or", "redirect", "to", "login", "prompt", "if", "none", "is", "available", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/docs/examples/resource_owner_grant.py#L95-L106
wndhydrnt/python-oauth2
docs/examples/resource_owner_grant.py
ClientApplication._login
def _login(self, failed=False): """ Login prompt """ if failed: content = self.LOGIN_TEMPLATE.format(failed_message="Login failed") else: content = self.LOGIN_TEMPLATE.format(failed_message="") return "200 OK", content, {"Content-Type": "text/html"}
python
def _login(self, failed=False): """ Login prompt """ if failed: content = self.LOGIN_TEMPLATE.format(failed_message="Login failed") else: content = self.LOGIN_TEMPLATE.format(failed_message="") return "200 OK", content, {"Content-Type": "text/html"}
[ "def", "_login", "(", "self", ",", "failed", "=", "False", ")", ":", "if", "failed", ":", "content", "=", "self", ".", "LOGIN_TEMPLATE", ".", "format", "(", "failed_message", "=", "\"Login failed\"", ")", "else", ":", "content", "=", "self", ".", "LOGIN_...
Login prompt
[ "Login", "prompt" ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/docs/examples/resource_owner_grant.py#L108-L116
wndhydrnt/python-oauth2
docs/examples/resource_owner_grant.py
ClientApplication._request_token
def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in post_params.items(): decoded_param = param.decode('utf-8') decoded_value = value[0].decode('utf-8') if decoded_param == "username" or decoded_param == "password": params[decoded_param] = decoded_value params["grant_type"] = "password" params["client_id"] = self.client_id params["client_secret"] = self.client_secret # Request an access token by POSTing a request to the auth server. try: response = urllib2.urlopen(self.token_endpoint, urlencode(params)) except HTTPError, he: if he.code == 400: error_body = json.loads(he.read()) body = self.SERVER_ERROR_TEMPLATE\ .format(error_type=error_body["error"], error_description=error_body["error_description"]) return "400 Bad Request", body, {"Content-Type": "text/html"} if he.code == 401: return "302 Found", "", {"Location": "/login?failed=1"} self.token = json.load(response) return "301 Moved", "", {"Location": "/"}
python
def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in post_params.items(): decoded_param = param.decode('utf-8') decoded_value = value[0].decode('utf-8') if decoded_param == "username" or decoded_param == "password": params[decoded_param] = decoded_value params["grant_type"] = "password" params["client_id"] = self.client_id params["client_secret"] = self.client_secret # Request an access token by POSTing a request to the auth server. try: response = urllib2.urlopen(self.token_endpoint, urlencode(params)) except HTTPError, he: if he.code == 400: error_body = json.loads(he.read()) body = self.SERVER_ERROR_TEMPLATE\ .format(error_type=error_body["error"], error_description=error_body["error_description"]) return "400 Bad Request", body, {"Content-Type": "text/html"} if he.code == 401: return "302 Found", "", {"Location": "/login?failed=1"} self.token = json.load(response) return "301 Moved", "", {"Location": "/"}
[ "def", "_request_token", "(", "self", ",", "env", ")", ":", "params", "=", "{", "}", "content", "=", "env", "[", "'wsgi.input'", "]", ".", "read", "(", "int", "(", "env", "[", "'CONTENT_LENGTH'", "]", ")", ")", "post_params", "=", "parse_qs", "(", "c...
Retrieves a new access token from the OAuth2 server.
[ "Retrieves", "a", "new", "access", "token", "from", "the", "OAuth2", "server", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/docs/examples/resource_owner_grant.py#L118-L151
wndhydrnt/python-oauth2
oauth2/store/memory.py
ClientStore.add_client
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to. """ self.clients[client_id] = Client( identifier=client_id, secret=client_secret, redirect_uris=redirect_uris, authorized_grants=authorized_grants, authorized_response_types=authorized_response_types) return True
python
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to. """ self.clients[client_id] = Client( identifier=client_id, secret=client_secret, redirect_uris=redirect_uris, authorized_grants=authorized_grants, authorized_response_types=authorized_response_types) return True
[ "def", "add_client", "(", "self", ",", "client_id", ",", "client_secret", ",", "redirect_uris", ",", "authorized_grants", "=", "None", ",", "authorized_response_types", "=", "None", ")", ":", "self", ".", "clients", "[", "client_id", "]", "=", "Client", "(", ...
Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication against the OAuth 2.0 provider. :param redirect_uris: A ``list`` of URIs to redirect to.
[ "Add", "a", "client", "app", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L21-L39
wndhydrnt/python-oauth2
oauth2/store/memory.py
ClientStore.fetch_by_client_id
def fetch_by_client_id(self, client_id): """ Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError """ if client_id not in self.clients: raise ClientNotFoundError return self.clients[client_id]
python
def fetch_by_client_id(self, client_id): """ Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError """ if client_id not in self.clients: raise ClientNotFoundError return self.clients[client_id]
[ "def", "fetch_by_client_id", "(", "self", ",", "client_id", ")", ":", "if", "client_id", "not", "in", "self", ".", "clients", ":", "raise", "ClientNotFoundError", "return", "self", ".", "clients", "[", "client_id", "]" ]
Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError
[ "Retrieve", "a", "client", "by", "its", "identifier", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L41-L53
wndhydrnt/python-oauth2
oauth2/store/memory.py
TokenStore.fetch_by_code
def fetch_by_code(self, code): """ Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. """ if code not in self.auth_codes: raise AuthCodeNotFound return self.auth_codes[code]
python
def fetch_by_code(self, code): """ Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. """ if code not in self.auth_codes: raise AuthCodeNotFound return self.auth_codes[code]
[ "def", "fetch_by_code", "(", "self", ",", "code", ")", ":", "if", "code", "not", "in", "self", ".", "auth_codes", ":", "raise", "AuthCodeNotFound", "return", "self", ".", "auth_codes", "[", "code", "]" ]
Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code.
[ "Returns", "an", "AuthorizationCode", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L69-L82
wndhydrnt/python-oauth2
oauth2/store/memory.py
TokenStore.save_token
def save_token(self, access_token): """ Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.unique_token_identifier[unique_token_key] = access_token.token if access_token.refresh_token is not None: self.refresh_tokens[access_token.refresh_token] = access_token return True
python
def save_token(self, access_token): """ Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.unique_token_identifier[unique_token_key] = access_token.token if access_token.refresh_token is not None: self.refresh_tokens[access_token.refresh_token] = access_token return True
[ "def", "save_token", "(", "self", ",", "access_token", ")", ":", "self", ".", "access_tokens", "[", "access_token", ".", "token", "]", "=", "access_token", "unique_token_key", "=", "self", ".", "_unique_token_key", "(", "access_token", ".", "client_id", ",", "...
Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`.
[ "Stores", "an", "access", "token", "and", "additional", "data", "in", "memory", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L96-L113
wndhydrnt/python-oauth2
oauth2/store/memory.py
TokenStore.fetch_by_refresh_token
def fetch_by_refresh_token(self, refresh_token): """ Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` """ if refresh_token not in self.refresh_tokens: raise AccessTokenNotFound return self.refresh_tokens[refresh_token]
python
def fetch_by_refresh_token(self, refresh_token): """ Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` """ if refresh_token not in self.refresh_tokens: raise AccessTokenNotFound return self.refresh_tokens[refresh_token]
[ "def", "fetch_by_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "if", "refresh_token", "not", "in", "self", ".", "refresh_tokens", ":", "raise", "AccessTokenNotFound", "return", "self", ".", "refresh_tokens", "[", "refresh_token", "]" ]
Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound`
[ "Find", "an", "access", "token", "by", "its", "refresh", "token", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memory.py#L131-L143
wndhydrnt/python-oauth2
oauth2/__init__.py
Provider.add_grant
def add_grant(self, grant): """ Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory """ if hasattr(grant, "expires_in"): self.token_generator.expires_in[grant.grant_type] = grant.expires_in if hasattr(grant, "refresh_expires_in"): self.token_generator.refresh_expires_in = grant.refresh_expires_in self.grant_types.append(grant)
python
def add_grant(self, grant): """ Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory """ if hasattr(grant, "expires_in"): self.token_generator.expires_in[grant.grant_type] = grant.expires_in if hasattr(grant, "refresh_expires_in"): self.token_generator.refresh_expires_in = grant.refresh_expires_in self.grant_types.append(grant)
[ "def", "add_grant", "(", "self", ",", "grant", ")", ":", "if", "hasattr", "(", "grant", ",", "\"expires_in\"", ")", ":", "self", ".", "token_generator", ".", "expires_in", "[", "grant", ".", "grant_type", "]", "=", "grant", ".", "expires_in", "if", "hasa...
Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory
[ "Adds", "a", "Grant", "that", "the", "provider", "should", "support", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/__init__.py#L83-L97
wndhydrnt/python-oauth2
oauth2/__init__.py
Provider.dispatch
def dispatch(self, request, environ): """ Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type request: :class:`oauth2.web.Request` :param environ: Dict containing variables of the environment. :type environ: dict :return: An instance of ``oauth2.web.Response``. """ try: grant_type = self._determine_grant_type(request) response = self.response_class() grant_type.read_validate_params(request) return grant_type.process(request, response, environ) except OAuthInvalidNoRedirectError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "invalid_redirect_uri", "error_description": "Invalid redirect URI" }) return response except OAuthInvalidError as err: response = self.response_class() return grant_type.handle_error(error=err, response=response) except UnsupportedGrantError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "unsupported_response_type", "error_description": "Grant not supported" }) return response except: app_log.error("Uncaught Exception", exc_info=True) response = self.response_class() return grant_type.handle_error( error=OAuthInvalidError(error="server_error", explanation="Internal server error"), response=response)
python
def dispatch(self, request, environ): """ Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type request: :class:`oauth2.web.Request` :param environ: Dict containing variables of the environment. :type environ: dict :return: An instance of ``oauth2.web.Response``. """ try: grant_type = self._determine_grant_type(request) response = self.response_class() grant_type.read_validate_params(request) return grant_type.process(request, response, environ) except OAuthInvalidNoRedirectError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "invalid_redirect_uri", "error_description": "Invalid redirect URI" }) return response except OAuthInvalidError as err: response = self.response_class() return grant_type.handle_error(error=err, response=response) except UnsupportedGrantError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "unsupported_response_type", "error_description": "Grant not supported" }) return response except: app_log.error("Uncaught Exception", exc_info=True) response = self.response_class() return grant_type.handle_error( error=OAuthInvalidError(error="server_error", explanation="Internal server error"), response=response)
[ "def", "dispatch", "(", "self", ",", "request", ",", "environ", ")", ":", "try", ":", "grant_type", "=", "self", ".", "_determine_grant_type", "(", "request", ")", "response", "=", "self", ".", "response_class", "(", ")", "grant_type", ".", "read_validate_pa...
Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type request: :class:`oauth2.web.Request` :param environ: Dict containing variables of the environment. :type environ: dict :return: An instance of ``oauth2.web.Response``.
[ "Checks", "which", "Grant", "supports", "the", "current", "request", "and", "dispatches", "to", "it", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/__init__.py#L99-L147
wndhydrnt/python-oauth2
oauth2/__init__.py
Provider.enable_unique_tokens
def enable_unique_tokens(self): """ Enable the use of unique access tokens on all grant types that support this option. """ for grant_type in self.grant_types: if hasattr(grant_type, "unique_token"): grant_type.unique_token = True
python
def enable_unique_tokens(self): """ Enable the use of unique access tokens on all grant types that support this option. """ for grant_type in self.grant_types: if hasattr(grant_type, "unique_token"): grant_type.unique_token = True
[ "def", "enable_unique_tokens", "(", "self", ")", ":", "for", "grant_type", "in", "self", ".", "grant_types", ":", "if", "hasattr", "(", "grant_type", ",", "\"unique_token\"", ")", ":", "grant_type", ".", "unique_token", "=", "True" ]
Enable the use of unique access tokens on all grant types that support this option.
[ "Enable", "the", "use", "of", "unique", "access", "tokens", "on", "all", "grant", "types", "that", "support", "this", "option", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/__init__.py#L149-L156
wndhydrnt/python-oauth2
oauth2/web/wsgi.py
Request.header
def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """ wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
python
def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """ wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
[ "def", "header", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "wsgi_header", "=", "\"HTTP_{0}\"", ".", "format", "(", "name", ".", "upper", "(", ")", ")", "try", ":", "return", "self", ".", "env_raw", "[", "wsgi_header", "]", "exc...
Returns the value of the HTTP header identified by `name`.
[ "Returns", "the", "value", "of", "the", "HTTP", "header", "identified", "by", "name", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/web/wsgi.py#L61-L70
wndhydrnt/python-oauth2
oauth2/client_authenticator.py
request_body
def request_body(request): """ Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of `(<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple """ client_id = request.post_param("client_id") if client_id is None: raise OAuthInvalidError(error="invalid_request", explanation="Missing client identifier") client_secret = request.post_param("client_secret") if client_secret is None: raise OAuthInvalidError(error="invalid_request", explanation="Missing client credentials") return client_id, client_secret
python
def request_body(request): """ Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of `(<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple """ client_id = request.post_param("client_id") if client_id is None: raise OAuthInvalidError(error="invalid_request", explanation="Missing client identifier") client_secret = request.post_param("client_secret") if client_secret is None: raise OAuthInvalidError(error="invalid_request", explanation="Missing client credentials") return client_id, client_secret
[ "def", "request_body", "(", "request", ")", ":", "client_id", "=", "request", ".", "post_param", "(", "\"client_id\"", ")", "if", "client_id", "is", "None", ":", "raise", "OAuthInvalidError", "(", "error", "=", "\"invalid_request\"", ",", "explanation", "=", "...
Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of `(<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple
[ "Extracts", "the", "credentials", "of", "a", "client", "from", "the", "*", "application", "/", "x", "-", "www", "-", "form", "-", "urlencoded", "*", "body", "of", "a", "request", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/client_authenticator.py#L96-L120
wndhydrnt/python-oauth2
oauth2/client_authenticator.py
http_basic_auth
def http_basic_auth(request): """ Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of (<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple """ auth_header = request.header("authorization") if auth_header is None: raise OAuthInvalidError(error="invalid_request", explanation="Authorization header is missing") auth_parts = auth_header.strip().encode("latin1").split(None) if auth_parts[0].strip().lower() != b'basic': raise OAuthInvalidError( error="invalid_request", explanation="Provider supports basic authentication only") client_id, client_secret = b64decode(auth_parts[1]).split(b':', 1) return client_id.decode("latin1"), client_secret.decode("latin1")
python
def http_basic_auth(request): """ Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of (<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple """ auth_header = request.header("authorization") if auth_header is None: raise OAuthInvalidError(error="invalid_request", explanation="Authorization header is missing") auth_parts = auth_header.strip().encode("latin1").split(None) if auth_parts[0].strip().lower() != b'basic': raise OAuthInvalidError( error="invalid_request", explanation="Provider supports basic authentication only") client_id, client_secret = b64decode(auth_parts[1]).split(b':', 1) return client_id.decode("latin1"), client_secret.decode("latin1")
[ "def", "http_basic_auth", "(", "request", ")", ":", "auth_header", "=", "request", ".", "header", "(", "\"authorization\"", ")", "if", "auth_header", "is", "None", ":", "raise", "OAuthInvalidError", "(", "error", "=", "\"invalid_request\"", ",", "explanation", "...
Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of (<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple
[ "Extracts", "the", "credentials", "of", "a", "client", "using", "HTTP", "Basic", "Auth", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/client_authenticator.py#L123-L151
wndhydrnt/python-oauth2
oauth2/client_authenticator.py
ClientAuthenticator.by_identifier
def by_identifier(self, request): """ Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises: :class OAuthInvalidNoRedirectError: """ client_id = request.get_param("client_id") if client_id is None: raise OAuthInvalidNoRedirectError(error="missing_client_id") try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidNoRedirectError(error="unknown_client") redirect_uri = request.get_param("redirect_uri") if redirect_uri is not None: try: client.redirect_uri = redirect_uri except RedirectUriUnknown: raise OAuthInvalidNoRedirectError( error="invalid_redirect_uri") return client
python
def by_identifier(self, request): """ Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises: :class OAuthInvalidNoRedirectError: """ client_id = request.get_param("client_id") if client_id is None: raise OAuthInvalidNoRedirectError(error="missing_client_id") try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidNoRedirectError(error="unknown_client") redirect_uri = request.get_param("redirect_uri") if redirect_uri is not None: try: client.redirect_uri = redirect_uri except RedirectUriUnknown: raise OAuthInvalidNoRedirectError( error="invalid_redirect_uri") return client
[ "def", "by_identifier", "(", "self", ",", "request", ")", ":", "client_id", "=", "request", ".", "get_param", "(", "\"client_id\"", ")", "if", "client_id", "is", "None", ":", "raise", "OAuthInvalidNoRedirectError", "(", "error", "=", "\"missing_client_id\"", ")"...
Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises: :class OAuthInvalidNoRedirectError:
[ "Authenticates", "a", "client", "by", "its", "identifier", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/client_authenticator.py#L29-L59
wndhydrnt/python-oauth2
oauth2/client_authenticator.py
ClientAuthenticator.by_identifier_secret
def by_identifier_secret(self, request): """ Authenticates a client by its identifier and secret (aka password). :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises OAuthInvalidError: If the client could not be found, is not allowed to to use the current grant or supplied invalid credentials """ client_id, client_secret = self.source(request=request) try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidError(error="invalid_client", explanation="No client could be found") grant_type = request.post_param("grant_type") if client.grant_type_supported(grant_type) is False: raise OAuthInvalidError(error="unauthorized_client", explanation="The client is not allowed " "to use this grant type") if client.secret != client_secret: raise OAuthInvalidError(error="invalid_client", explanation="Invalid client credentials") return client
python
def by_identifier_secret(self, request): """ Authenticates a client by its identifier and secret (aka password). :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises OAuthInvalidError: If the client could not be found, is not allowed to to use the current grant or supplied invalid credentials """ client_id, client_secret = self.source(request=request) try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidError(error="invalid_client", explanation="No client could be found") grant_type = request.post_param("grant_type") if client.grant_type_supported(grant_type) is False: raise OAuthInvalidError(error="unauthorized_client", explanation="The client is not allowed " "to use this grant type") if client.secret != client_secret: raise OAuthInvalidError(error="invalid_client", explanation="Invalid client credentials") return client
[ "def", "by_identifier_secret", "(", "self", ",", "request", ")", ":", "client_id", ",", "client_secret", "=", "self", ".", "source", "(", "request", "=", "request", ")", "try", ":", "client", "=", "self", ".", "client_store", ".", "fetch_by_client_id", "(", ...
Authenticates a client by its identifier and secret (aka password). :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises OAuthInvalidError: If the client could not be found, is not allowed to to use the current grant or supplied invalid credentials
[ "Authenticates", "a", "client", "by", "its", "identifier", "and", "secret", "(", "aka", "password", ")", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/client_authenticator.py#L61-L93
wndhydrnt/python-oauth2
oauth2/datatype.py
AccessToken.expires_in
def expires_in(self): """ Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired. """ time_left = self.expires_at - int(time.time()) if time_left > 0: return time_left return 0
python
def expires_in(self): """ Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired. """ time_left = self.expires_at - int(time.time()) if time_left > 0: return time_left return 0
[ "def", "expires_in", "(", "self", ")", ":", "time_left", "=", "self", ".", "expires_at", "-", "int", "(", "time", ".", "time", "(", ")", ")", "if", "time_left", ">", "0", ":", "return", "time_left", "return", "0" ]
Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired.
[ "Returns", "the", "time", "until", "the", "token", "expires", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/datatype.py#L28-L39
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DatabaseStore.execute
def execute(self, query, *params): """ Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `long` identifying the last altered row. """ cursor = self.connection.cursor() try: cursor.execute(query, params) self.connection.commit() return cursor.lastrowid finally: cursor.close()
python
def execute(self, query, *params): """ Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `long` identifying the last altered row. """ cursor = self.connection.cursor() try: cursor.execute(query, params) self.connection.commit() return cursor.lastrowid finally: cursor.close()
[ "def", "execute", "(", "self", ",", "query", ",", "*", "params", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "query", ",", "params", ")", "self", ".", "connection", ".", "c...
Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `long` identifying the last altered row.
[ "Executes", "a", "query", "and", "returns", "the", "identifier", "of", "the", "modified", "row", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L25-L43
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DatabaseStore.fetchone
def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row with each field being one element in a `tuple`. """ cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchone() finally: cursor.close()
python
def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row with each field being one element in a `tuple`. """ cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchone() finally: cursor.close()
[ "def", "fetchone", "(", "self", ",", "query", ",", "*", "args", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "query", ",", "args", ")", "return", "cursor", ".", "fetchone", ...
Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row with each field being one element in a `tuple`.
[ "Returns", "the", "first", "result", "of", "the", "given", "query", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L45-L62
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DatabaseStore.fetchall
def fetchall(self, query, *args): """ Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with each field being one element in the `tuple`. """ cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchall() finally: cursor.close()
python
def fetchall(self, query, *args): """ Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with each field being one element in the `tuple`. """ cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchall() finally: cursor.close()
[ "def", "fetchall", "(", "self", ",", "query", ",", "*", "args", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "query", ",", "args", ")", "return", "cursor", ".", "fetchall", ...
Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with each field being one element in the `tuple`.
[ "Returns", "all", "results", "of", "the", "given", "query", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L64-L81
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiAccessTokenStore.fetch_by_refresh_token
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved. """ row = self.fetchone(self.fetch_by_refresh_token_query, refresh_token) if row is None: raise AccessTokenNotFound scopes = self._fetch_scopes(access_token_id=row[0]) data = self._fetch_data(access_token_id=row[0]) return self._row_to_token(data=data, scopes=scopes, row=row)
python
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved. """ row = self.fetchone(self.fetch_by_refresh_token_query, refresh_token) if row is None: raise AccessTokenNotFound scopes = self._fetch_scopes(access_token_id=row[0]) data = self._fetch_data(access_token_id=row[0]) return self._row_to_token(data=data, scopes=scopes, row=row)
[ "def", "fetch_by_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "row", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_by_refresh_token_query", ",", "refresh_token", ")", "if", "row", "is", "None", ":", "raise", "AccessTokenNotFound", "scope...
Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved.
[ "Retrieves", "an", "access", "token", "by", "its", "refresh", "token", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L118-L138
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiAccessTokenStore.fetch_existing_token_of_user
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved. """ token_data = self.fetchone(self.fetch_existing_token_of_user_query, client_id, grant_type, user_id) if token_data is None: raise AccessTokenNotFound scopes = self._fetch_scopes(access_token_id=token_data[0]) data = self._fetch_data(access_token_id=token_data[0]) return self._row_to_token(data=data, scopes=scopes, row=token_data)
python
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved. """ token_data = self.fetchone(self.fetch_existing_token_of_user_query, client_id, grant_type, user_id) if token_data is None: raise AccessTokenNotFound scopes = self._fetch_scopes(access_token_id=token_data[0]) data = self._fetch_data(access_token_id=token_data[0]) return self._row_to_token(data=data, scopes=scopes, row=token_data)
[ "def", "fetch_existing_token_of_user", "(", "self", ",", "client_id", ",", "grant_type", ",", "user_id", ")", ":", "token_data", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_existing_token_of_user_query", ",", "client_id", ",", "grant_type", ",", "user_i...
Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved.
[ "Retrieve", "an", "access", "token", "issued", "to", "a", "client", "and", "user", "for", "a", "specific", "grant", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L140-L165
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiAccessTokenStore.save_token
def save_token(self, access_token): """ Creates a new entry for an access token in the database. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. :return: `True`. """ access_token_id = self.execute(self.create_access_token_query, access_token.client_id, access_token.grant_type, access_token.token, access_token.expires_at, access_token.refresh_token, access_token.refresh_expires_at, access_token.user_id) for key, value in list(access_token.data.items()): self.execute(self.create_data_query, key, value, access_token_id) for scope in access_token.scopes: self.execute(self.create_scope_query, scope, access_token_id) return True
python
def save_token(self, access_token): """ Creates a new entry for an access token in the database. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. :return: `True`. """ access_token_id = self.execute(self.create_access_token_query, access_token.client_id, access_token.grant_type, access_token.token, access_token.expires_at, access_token.refresh_token, access_token.refresh_expires_at, access_token.user_id) for key, value in list(access_token.data.items()): self.execute(self.create_data_query, key, value, access_token_id) for scope in access_token.scopes: self.execute(self.create_scope_query, scope, access_token_id) return True
[ "def", "save_token", "(", "self", ",", "access_token", ")", ":", "access_token_id", "=", "self", ".", "execute", "(", "self", ".", "create_access_token_query", ",", "access_token", ".", "client_id", ",", "access_token", ".", "grant_type", ",", "access_token", "....
Creates a new entry for an access token in the database. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. :return: `True`.
[ "Creates", "a", "new", "entry", "for", "an", "access", "token", "in", "the", "database", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L167-L192
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiAuthCodeStore.fetch_by_code
def fetch_by_code(self, code): """ Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could be retrieved. """ auth_code_data = self.fetchone(self.fetch_code_query, code) if auth_code_data is None: raise AuthCodeNotFound data = dict() data_result = self.fetchall(self.fetch_data_query, auth_code_data[0]) if data_result is not None: for dataset in data_result: data[dataset[0]] = dataset[1] scopes = [] scope_result = self.fetchall(self.fetch_scopes_query, auth_code_data[0]) if scope_result is not None: for scope_set in scope_result: scopes.append(scope_set[0]) return AuthorizationCode(client_id=auth_code_data[1], code=auth_code_data[2], expires_at=auth_code_data[3], redirect_uri=auth_code_data[4], scopes=scopes, data=data, user_id=auth_code_data[5])
python
def fetch_by_code(self, code): """ Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could be retrieved. """ auth_code_data = self.fetchone(self.fetch_code_query, code) if auth_code_data is None: raise AuthCodeNotFound data = dict() data_result = self.fetchall(self.fetch_data_query, auth_code_data[0]) if data_result is not None: for dataset in data_result: data[dataset[0]] = dataset[1] scopes = [] scope_result = self.fetchall(self.fetch_scopes_query, auth_code_data[0]) if scope_result is not None: for scope_set in scope_result: scopes.append(scope_set[0]) return AuthorizationCode(client_id=auth_code_data[1], code=auth_code_data[2], expires_at=auth_code_data[3], redirect_uri=auth_code_data[4], scopes=scopes, data=data, user_id=auth_code_data[5])
[ "def", "fetch_by_code", "(", "self", ",", "code", ")", ":", "auth_code_data", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_code_query", ",", "code", ")", "if", "auth_code_data", "is", "None", ":", "raise", "AuthCodeNotFound", "data", "=", "dict", ...
Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could be retrieved.
[ "Retrieves", "an", "auth", "code", "by", "its", "code", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L250-L284
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiAuthCodeStore.save_code
def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """ auth_code_id = self.execute(self.create_auth_code_query, authorization_code.client_id, authorization_code.code, authorization_code.expires_at, authorization_code.redirect_uri, authorization_code.user_id) for key, value in list(authorization_code.data.items()): self.execute(self.create_data_query, key, value, auth_code_id) for scope in authorization_code.scopes: self.execute(self.create_scope_query, scope, auth_code_id) return True
python
def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """ auth_code_id = self.execute(self.create_auth_code_query, authorization_code.client_id, authorization_code.code, authorization_code.expires_at, authorization_code.redirect_uri, authorization_code.user_id) for key, value in list(authorization_code.data.items()): self.execute(self.create_data_query, key, value, auth_code_id) for scope in authorization_code.scopes: self.execute(self.create_scope_query, scope, auth_code_id) return True
[ "def", "save_code", "(", "self", ",", "authorization_code", ")", ":", "auth_code_id", "=", "self", ".", "execute", "(", "self", ".", "create_auth_code_query", ",", "authorization_code", ".", "client_id", ",", "authorization_code", ".", "code", ",", "authorization_...
Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine.
[ "Creates", "a", "new", "entry", "of", "an", "auth", "code", "in", "the", "database", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L286-L308
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
DbApiClientStore.fetch_by_client_id
def fetch_by_client_id(self, client_id): """ Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved. """ grants = None redirect_uris = None response_types = None client_data = self.fetchone(self.fetch_client_query, client_id) if client_data is None: raise ClientNotFoundError grant_data = self.fetchall(self.fetch_grants_query, client_data[0]) if grant_data: grants = [] for grant in grant_data: grants.append(grant[0]) redirect_uris_data = self.fetchall(self.fetch_redirect_uris_query, client_data[0]) if redirect_uris_data: redirect_uris = [] for redirect_uri in redirect_uris_data: redirect_uris.append(redirect_uri[0]) response_types_data = self.fetchall(self.fetch_response_types_query, client_data[0]) if response_types_data: response_types = [] for response_type in response_types_data: response_types.append(response_type[0]) return Client(identifier=client_data[1], secret=client_data[2], authorized_grants=grants, authorized_response_types=response_types, redirect_uris=redirect_uris)
python
def fetch_by_client_id(self, client_id): """ Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved. """ grants = None redirect_uris = None response_types = None client_data = self.fetchone(self.fetch_client_query, client_id) if client_data is None: raise ClientNotFoundError grant_data = self.fetchall(self.fetch_grants_query, client_data[0]) if grant_data: grants = [] for grant in grant_data: grants.append(grant[0]) redirect_uris_data = self.fetchall(self.fetch_redirect_uris_query, client_data[0]) if redirect_uris_data: redirect_uris = [] for redirect_uri in redirect_uris_data: redirect_uris.append(redirect_uri[0]) response_types_data = self.fetchall(self.fetch_response_types_query, client_data[0]) if response_types_data: response_types = [] for response_type in response_types_data: response_types.append(response_type[0]) return Client(identifier=client_data[1], secret=client_data[2], authorized_grants=grants, authorized_response_types=response_types, redirect_uris=redirect_uris)
[ "def", "fetch_by_client_id", "(", "self", ",", "client_id", ")", ":", "grants", "=", "None", "redirect_uris", "=", "None", "response_types", "=", "None", "client_data", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_client_query", ",", "client_id", ")"...
Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved.
[ "Retrieves", "a", "client", "by", "its", "identifier", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L327-L370
wndhydrnt/python-oauth2
oauth2/store/memcache.py
TokenStore.fetch_by_code
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.mc.get(self._generate_cache_key(code)) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
python
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.mc.get(self._generate_cache_key(code)) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
[ "def", "fetch_by_code", "(", "self", ",", "code", ")", ":", "code_data", "=", "self", ".", "mc", ".", "get", "(", "self", ".", "_generate_cache_key", "(", "code", ")", ")", "if", "code_data", "is", "None", ":", "raise", "AuthCodeNotFound", "return", "Aut...
Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`.
[ "Returns", "data", "belonging", "to", "an", "authorization", "code", "from", "memcache", "or", "None", "if", "no", "data", "was", "found", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memcache.py#L39-L52
wndhydrnt/python-oauth2
oauth2/store/memcache.py
TokenStore.save_code
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
python
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
[ "def", "save_code", "(", "self", ",", "authorization_code", ")", ":", "key", "=", "self", ".", "_generate_cache_key", "(", "authorization_code", ".", "code", ")", "self", ".", "mc", ".", "set", "(", "key", ",", "{", "\"client_id\"", ":", "authorization_code"...
Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`.
[ "Stores", "the", "data", "belonging", "to", "an", "authorization", "code", "token", "in", "memcache", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memcache.py#L54-L69
wndhydrnt/python-oauth2
oauth2/store/memcache.py
TokenStore.save_token
def save_token(self, access_token): """ Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """ key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.mc.set(self._generate_cache_key(unique_token_key), access_token.__dict__) if access_token.refresh_token is not None: rft_key = self._generate_cache_key(access_token.refresh_token) self.mc.set(rft_key, access_token.__dict__)
python
def save_token(self, access_token): """ Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """ key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.mc.set(self._generate_cache_key(unique_token_key), access_token.__dict__) if access_token.refresh_token is not None: rft_key = self._generate_cache_key(access_token.refresh_token) self.mc.set(rft_key, access_token.__dict__)
[ "def", "save_token", "(", "self", ",", "access_token", ")", ":", "key", "=", "self", ".", "_generate_cache_key", "(", "access_token", ".", "token", ")", "self", ".", "mc", ".", "set", "(", "key", ",", "access_token", ".", "__dict__", ")", "unique_token_key...
Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`.
[ "Stores", "the", "access", "token", "and", "additional", "data", "in", "memcache", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memcache.py#L78-L96
wndhydrnt/python-oauth2
oauth2/store/memcache.py
TokenStore.delete_refresh_token
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.mc.delete(self._generate_cache_key(access_token.token)) self.mc.delete(self._generate_cache_key(refresh_token))
python
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.mc.delete(self._generate_cache_key(access_token.token)) self.mc.delete(self._generate_cache_key(refresh_token))
[ "def", "delete_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "access_token", "=", "self", ".", "fetch_by_refresh_token", "(", "refresh_token", ")", "self", ".", "mc", ".", "delete", "(", "self", ".", "_generate_cache_key", "(", "access_token", "."...
Deletes a refresh token after use :param refresh_token: The refresh token to delete.
[ "Deletes", "a", "refresh", "token", "after", "use", ":", "param", "refresh_token", ":", "The", "refresh", "token", "to", "delete", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memcache.py#L98-L105
wndhydrnt/python-oauth2
oauth2/grant.py
encode_scopes
def encode_scopes(scopes, use_quote=False): """ Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string """ scopes_as_string = Scope.separator.join(scopes) if use_quote: return quote(scopes_as_string) return scopes_as_string
python
def encode_scopes(scopes, use_quote=False): """ Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string """ scopes_as_string = Scope.separator.join(scopes) if use_quote: return quote(scopes_as_string) return scopes_as_string
[ "def", "encode_scopes", "(", "scopes", ",", "use_quote", "=", "False", ")", ":", "scopes_as_string", "=", "Scope", ".", "separator", ".", "join", "(", "scopes", ")", "if", "use_quote", ":", "return", "quote", "(", "scopes_as_string", ")", "return", "scopes_a...
Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string
[ "Creates", "a", "string", "out", "of", "a", "list", "of", "scopes", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L41-L53
wndhydrnt/python-oauth2
oauth2/grant.py
json_error_response
def json_error_response(error, response, status_code=400): """ Formats an error as a response containing a JSON body. """ msg = {"error": error.error, "error_description": error.explanation} response.status_code = status_code response.add_header("Content-Type", "application/json") response.body = json.dumps(msg) return response
python
def json_error_response(error, response, status_code=400): """ Formats an error as a response containing a JSON body. """ msg = {"error": error.error, "error_description": error.explanation} response.status_code = status_code response.add_header("Content-Type", "application/json") response.body = json.dumps(msg) return response
[ "def", "json_error_response", "(", "error", ",", "response", ",", "status_code", "=", "400", ")", ":", "msg", "=", "{", "\"error\"", ":", "error", ".", "error", ",", "\"error_description\"", ":", "error", ".", "explanation", "}", "response", ".", "status_cod...
Formats an error as a response containing a JSON body.
[ "Formats", "an", "error", "as", "a", "response", "containing", "a", "JSON", "body", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L56-L66
wndhydrnt/python-oauth2
oauth2/grant.py
json_success_response
def json_success_response(data, response): """ Formats the response of a successful token request as JSON. Also adds default headers and status code. """ response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_header("Cache-Control", "no-store") response.add_header("Pragma", "no-cache")
python
def json_success_response(data, response): """ Formats the response of a successful token request as JSON. Also adds default headers and status code. """ response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_header("Cache-Control", "no-store") response.add_header("Pragma", "no-cache")
[ "def", "json_success_response", "(", "data", ",", "response", ")", ":", "response", ".", "body", "=", "json", ".", "dumps", "(", "data", ")", "response", ".", "status_code", "=", "200", "response", ".", "add_header", "(", "\"Content-Type\"", ",", "\"applicat...
Formats the response of a successful token request as JSON. Also adds default headers and status code.
[ "Formats", "the", "response", "of", "a", "successful", "token", "request", "as", "JSON", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L69-L80
wndhydrnt/python-oauth2
oauth2/grant.py
Scope.compare
def compare(self, previous_scopes): """ Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: ``True`` """ for scope in self.scopes: if scope not in previous_scopes: raise OAuthInvalidError( error="invalid_scope", explanation="Invalid scope parameter in request") return True
python
def compare(self, previous_scopes): """ Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: ``True`` """ for scope in self.scopes: if scope not in previous_scopes: raise OAuthInvalidError( error="invalid_scope", explanation="Invalid scope parameter in request") return True
[ "def", "compare", "(", "self", ",", "previous_scopes", ")", ":", "for", "scope", "in", "self", ".", "scopes", ":", "if", "scope", "not", "in", "previous_scopes", ":", "raise", "OAuthInvalidError", "(", "error", "=", "\"invalid_scope\"", ",", "explanation", "...
Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: ``True``
[ "Compares", "the", "scopes", "read", "from", "request", "with", "previously", "issued", "scopes", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L113-L126
wndhydrnt/python-oauth2
oauth2/grant.py
Scope.parse
def parse(self, request, source): """ Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each requested scope is separated by a white space:: # One scope requested "profile_read" # Multiple scopes "profile_read profile_write" :param request: An instance of :class:`oauth2.web.Request`. :param source: Where to read the scope from. Pass "body" in case of a application/x-www-form-urlencoded body and "query" in case the scope is supplied as a query parameter in the URL of a request. """ if source == "body": req_scope = request.post_param("scope") elif source == "query": req_scope = request.get_param("scope") else: raise ValueError("Unknown scope source '" + source + "'") if req_scope is None: if self.default is not None: self.scopes = [self.default] self.send_back = True return elif len(self.available_scopes) != 0: raise OAuthInvalidError( error="invalid_scope", explanation="Missing scope parameter in request") else: return req_scopes = req_scope.split(self.separator) self.scopes = [scope for scope in req_scopes if scope in self.available_scopes] if len(self.scopes) == 0 and self.default is not None: self.scopes = [self.default] self.send_back = True
python
def parse(self, request, source): """ Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each requested scope is separated by a white space:: # One scope requested "profile_read" # Multiple scopes "profile_read profile_write" :param request: An instance of :class:`oauth2.web.Request`. :param source: Where to read the scope from. Pass "body" in case of a application/x-www-form-urlencoded body and "query" in case the scope is supplied as a query parameter in the URL of a request. """ if source == "body": req_scope = request.post_param("scope") elif source == "query": req_scope = request.get_param("scope") else: raise ValueError("Unknown scope source '" + source + "'") if req_scope is None: if self.default is not None: self.scopes = [self.default] self.send_back = True return elif len(self.available_scopes) != 0: raise OAuthInvalidError( error="invalid_scope", explanation="Missing scope parameter in request") else: return req_scopes = req_scope.split(self.separator) self.scopes = [scope for scope in req_scopes if scope in self.available_scopes] if len(self.scopes) == 0 and self.default is not None: self.scopes = [self.default] self.send_back = True
[ "def", "parse", "(", "self", ",", "request", ",", "source", ")", ":", "if", "source", "==", "\"body\"", ":", "req_scope", "=", "request", ".", "post_param", "(", "\"scope\"", ")", "elif", "source", "==", "\"query\"", ":", "req_scope", "=", "request", "."...
Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each requested scope is separated by a white space:: # One scope requested "profile_read" # Multiple scopes "profile_read profile_write" :param request: An instance of :class:`oauth2.web.Request`. :param source: Where to read the scope from. Pass "body" in case of a application/x-www-form-urlencoded body and "query" in case the scope is supplied as a query parameter in the URL of a request.
[ "Parses", "scope", "value", "in", "given", "request", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L128-L173
wndhydrnt/python-oauth2
oauth2/grant.py
AuthRequestMixin.read_validate_params
def read_validate_params(self, request): """ Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant. """ self.client = self.client_authenticator.by_identifier(request) response_type = request.get_param("response_type") if self.client.response_type_supported(response_type) is False: raise OAuthInvalidError(error="unauthorized_client") self.state = request.get_param("state") self.scope_handler.parse(request, "query") return True
python
def read_validate_params(self, request): """ Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant. """ self.client = self.client_authenticator.by_identifier(request) response_type = request.get_param("response_type") if self.client.response_type_supported(response_type) is False: raise OAuthInvalidError(error="unauthorized_client") self.state = request.get_param("state") self.scope_handler.parse(request, "query") return True
[ "def", "read_validate_params", "(", "self", ",", "request", ")", ":", "self", ".", "client", "=", "self", ".", "client_authenticator", ".", "by_identifier", "(", "request", ")", "response_type", "=", "request", ".", "get_param", "(", "\"response_type\"", ")", ...
Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant.
[ "Reads", "and", "validates", "data", "in", "an", "incoming", "request", "as", "required", "by", "the", "Authorization", "Request", "of", "the", "Authorization", "Code", "Grant", "and", "the", "Implicit", "Grant", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L262-L279
wndhydrnt/python-oauth2
oauth2/grant.py
AuthorizeMixin.authorize
def authorize(self, request, response, environ, scopes): """ Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually :param environ: The environment variables of this request :param scopes: The scopes requested by an application :return: A tuple containing (`dict`, user_id) or the response. """ if self.site_adapter.user_has_denied_access(request) is True: raise OAuthInvalidError(error="access_denied", explanation="Authorization denied by user") try: result = self.site_adapter.authenticate(request, environ, scopes, self.client) return self.sanitize_return_value(result) except UserNotAuthenticated: return self.site_adapter.render_auth_page(request, response, environ, scopes, self.client)
python
def authorize(self, request, response, environ, scopes): """ Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually :param environ: The environment variables of this request :param scopes: The scopes requested by an application :return: A tuple containing (`dict`, user_id) or the response. """ if self.site_adapter.user_has_denied_access(request) is True: raise OAuthInvalidError(error="access_denied", explanation="Authorization denied by user") try: result = self.site_adapter.authenticate(request, environ, scopes, self.client) return self.sanitize_return_value(result) except UserNotAuthenticated: return self.site_adapter.render_auth_page(request, response, environ, scopes, self.client)
[ "def", "authorize", "(", "self", ",", "request", ",", "response", ",", "environ", ",", "scopes", ")", ":", "if", "self", ".", "site_adapter", ".", "user_has_denied_access", "(", "request", ")", "is", "True", ":", "raise", "OAuthInvalidError", "(", "error", ...
Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually :param environ: The environment variables of this request :param scopes: The scopes requested by an application :return: A tuple containing (`dict`, user_id) or the response.
[ "Controls", "all", "steps", "to", "authorize", "a", "request", "by", "a", "user", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L292-L316
wndhydrnt/python-oauth2
oauth2/grant.py
AuthorizationCodeAuthHandler.process
def process(self, request, response, environ): """ Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`. """ data = self.authorize(request, response, environ, self.scope_handler.scopes) if isinstance(data, Response): return data code = self.token_generator.generate() expires = int(time.time()) + self.token_expiration auth_code = AuthorizationCode(client_id=self.client.identifier, code=code, expires_at=expires, redirect_uri=self.client.redirect_uri, scopes=self.scope_handler.scopes, data=data[0], user_id=data[1]) self.auth_code_store.save_code(auth_code) response.add_header("Location", self._generate_location(code)) response.body = "" response.status_code = 302 return response
python
def process(self, request, response, environ): """ Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`. """ data = self.authorize(request, response, environ, self.scope_handler.scopes) if isinstance(data, Response): return data code = self.token_generator.generate() expires = int(time.time()) + self.token_expiration auth_code = AuthorizationCode(client_id=self.client.identifier, code=code, expires_at=expires, redirect_uri=self.client.redirect_uri, scopes=self.scope_handler.scopes, data=data[0], user_id=data[1]) self.auth_code_store.save_code(auth_code) response.add_header("Location", self._generate_location(code)) response.body = "" response.status_code = 302 return response
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "data", "=", "self", ".", "authorize", "(", "request", ",", "response", ",", "environ", ",", "self", ".", "scope_handler", ".", "scopes", ")", "if", "isinstance", ...
Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`.
[ "Generates", "a", "new", "authorization", "token", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L421-L449
wndhydrnt/python-oauth2
oauth2/grant.py
AuthorizationCodeAuthHandler.handle_error
def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """ query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_code = 302 response.body = "" response.add_header("Location", location) return response
python
def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """ query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_code = 302 response.body = "" response.add_header("Location", location) return response
[ "def", "handle_error", "(", "self", ",", "error", ",", "response", ")", ":", "query_params", "=", "{", "\"error\"", ":", "error", ".", "error", "}", "query", "=", "urlencode", "(", "query_params", ")", "location", "=", "\"%s?%s\"", "%", "(", "self", ".",...
Redirects the client in case an error in the auth process occurred.
[ "Redirects", "the", "client", "in", "case", "an", "error", "in", "the", "auth", "process", "occurred", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L451-L465
wndhydrnt/python-oauth2
oauth2/grant.py
AuthorizationCodeTokenHandler.process
def process(self, request, response, environ): """ Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls `oauth2.store.AccessTokenStore` to persist the token. """ token_data = self.create_token( client_id=self.client.identifier, data=self.data, grant_type=AuthorizationCodeGrant.grant_type, scopes=self.scopes, user_id=self.user_id) self.auth_code_store.delete_code(self.code) if self.scopes: token_data["scope"] = encode_scopes(self.scopes) json_success_response(data=token_data, response=response) return response
python
def process(self, request, response, environ): """ Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls `oauth2.store.AccessTokenStore` to persist the token. """ token_data = self.create_token( client_id=self.client.identifier, data=self.data, grant_type=AuthorizationCodeGrant.grant_type, scopes=self.scopes, user_id=self.user_id) self.auth_code_store.delete_code(self.code) if self.scopes: token_data["scope"] = encode_scopes(self.scopes) json_success_response(data=token_data, response=response) return response
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "token_data", "=", "self", ".", "create_token", "(", "client_id", "=", "self", ".", "client", ".", "identifier", ",", "data", "=", "self", ".", "data", ",", "gran...
Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls `oauth2.store.AccessTokenStore` to persist the token.
[ "Generates", "a", "new", "access", "token", "and", "returns", "it", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L512-L534
wndhydrnt/python-oauth2
oauth2/grant.py
ResourceOwnerGrantHandler.process
def process(self, request, response, environ): """ Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation. """ try: data = self.site_adapter.authenticate(request, environ, self.scope_handler.scopes, self.client) data = AuthorizeMixin.sanitize_return_value(data) except UserNotAuthenticated: raise OAuthInvalidError(error="invalid_client", explanation=self.OWNER_NOT_AUTHENTICATED) if isinstance(data, Response): return data token_data = self.create_token( client_id=self.client.identifier, data=data[0], grant_type=ResourceOwnerGrant.grant_type, scopes=self.scope_handler.scopes, user_id=data[1]) if self.scope_handler.send_back: token_data["scope"] = encode_scopes(self.scope_handler.scopes) json_success_response(data=token_data, response=response) return response
python
def process(self, request, response, environ): """ Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation. """ try: data = self.site_adapter.authenticate(request, environ, self.scope_handler.scopes, self.client) data = AuthorizeMixin.sanitize_return_value(data) except UserNotAuthenticated: raise OAuthInvalidError(error="invalid_client", explanation=self.OWNER_NOT_AUTHENTICATED) if isinstance(data, Response): return data token_data = self.create_token( client_id=self.client.identifier, data=data[0], grant_type=ResourceOwnerGrant.grant_type, scopes=self.scope_handler.scopes, user_id=data[1]) if self.scope_handler.send_back: token_data["scope"] = encode_scopes(self.scope_handler.scopes) json_success_response(data=token_data, response=response) return response
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "try", ":", "data", "=", "self", ".", "site_adapter", ".", "authenticate", "(", "request", ",", "environ", ",", "self", ".", "scope_handler", ".", "scopes", ",", ...
Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation.
[ "Takes", "the", "incoming", "request", "asks", "the", "concrete", "SiteAdapter", "to", "validate", "it", "and", "issues", "a", "new", "access", "token", "that", "is", "returned", "to", "the", "client", "on", "successful", "validation", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L813-L843
wndhydrnt/python-oauth2
oauth2/grant.py
ResourceOwnerGrantHandler.read_validate_params
def read_validate_params(self, request): """ Checks if all incoming parameters meet the expected values. """ self.client = self.client_authenticator.by_identifier_secret(request) self.password = request.post_param("password") self.username = request.post_param("username") self.scope_handler.parse(request=request, source="body") return True
python
def read_validate_params(self, request): """ Checks if all incoming parameters meet the expected values. """ self.client = self.client_authenticator.by_identifier_secret(request) self.password = request.post_param("password") self.username = request.post_param("username") self.scope_handler.parse(request=request, source="body") return True
[ "def", "read_validate_params", "(", "self", ",", "request", ")", ":", "self", ".", "client", "=", "self", ".", "client_authenticator", ".", "by_identifier_secret", "(", "request", ")", "self", ".", "password", "=", "request", ".", "post_param", "(", "\"passwor...
Checks if all incoming parameters meet the expected values.
[ "Checks", "if", "all", "incoming", "parameters", "meet", "the", "expected", "values", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L845-L856
wndhydrnt/python-oauth2
oauth2/grant.py
RefreshTokenHandler.process
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` containing data of the environment. :return: :class:`oauth2.web.Response` """ token_data = self.token_generator.create_access_token_data(self.refresh_grant_type) expires_at = int(time.time()) + token_data["expires_in"] access_token = AccessToken(client_id=self.client.identifier, token=token_data["access_token"], grant_type=self.refresh_grant_type, data=self.data, expires_at=expires_at, scopes=self.scope_handler.scopes, user_id=self.user_id) if self.reissue_refresh_tokens: self.access_token_store.delete_refresh_token(self.refresh_token) access_token.refresh_token = token_data["refresh_token"] refresh_expires_in = self.token_generator.refresh_expires_in refresh_expires_at = int(time.time()) + refresh_expires_in access_token.refresh_expires_at = refresh_expires_at else: del token_data["refresh_token"] self.access_token_store.save_token(access_token) json_success_response(data=token_data, response=response) return response
python
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` containing data of the environment. :return: :class:`oauth2.web.Response` """ token_data = self.token_generator.create_access_token_data(self.refresh_grant_type) expires_at = int(time.time()) + token_data["expires_in"] access_token = AccessToken(client_id=self.client.identifier, token=token_data["access_token"], grant_type=self.refresh_grant_type, data=self.data, expires_at=expires_at, scopes=self.scope_handler.scopes, user_id=self.user_id) if self.reissue_refresh_tokens: self.access_token_store.delete_refresh_token(self.refresh_token) access_token.refresh_token = token_data["refresh_token"] refresh_expires_in = self.token_generator.refresh_expires_in refresh_expires_at = int(time.time()) + refresh_expires_in access_token.refresh_expires_at = refresh_expires_at else: del token_data["refresh_token"] self.access_token_store.save_token(access_token) json_success_response(data=token_data, response=response) return response
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "token_data", "=", "self", ".", "token_generator", ".", "create_access_token_data", "(", "self", ".", "refresh_grant_type", ")", "expires_at", "=", "int", "(", "time", ...
Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` containing data of the environment. :return: :class:`oauth2.web.Response`
[ "Create", "a", "new", "access", "token", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L936-L971
wndhydrnt/python-oauth2
oauth2/grant.py
RefreshTokenHandler.read_validate_params
def read_validate_params(self, request): """ Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError` """ self.refresh_token = request.post_param("refresh_token") if self.refresh_token is None: raise OAuthInvalidError( error="invalid_request", explanation="Missing refresh_token in request body") self.client = self.client_authenticator.by_identifier_secret(request) try: access_token = self.access_token_store.fetch_by_refresh_token( self.refresh_token ) except AccessTokenNotFound: raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") refresh_token_expires_at = access_token.refresh_expires_at self.refresh_grant_type = access_token.grant_type if refresh_token_expires_at != 0 and \ refresh_token_expires_at < int(time.time()): raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") self.data = access_token.data self.user_id = access_token.user_id self.scope_handler.parse(request, "body") self.scope_handler.compare(access_token.scopes) return True
python
def read_validate_params(self, request): """ Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError` """ self.refresh_token = request.post_param("refresh_token") if self.refresh_token is None: raise OAuthInvalidError( error="invalid_request", explanation="Missing refresh_token in request body") self.client = self.client_authenticator.by_identifier_secret(request) try: access_token = self.access_token_store.fetch_by_refresh_token( self.refresh_token ) except AccessTokenNotFound: raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") refresh_token_expires_at = access_token.refresh_expires_at self.refresh_grant_type = access_token.grant_type if refresh_token_expires_at != 0 and \ refresh_token_expires_at < int(time.time()): raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") self.data = access_token.data self.user_id = access_token.user_id self.scope_handler.parse(request, "body") self.scope_handler.compare(access_token.scopes) return True
[ "def", "read_validate_params", "(", "self", ",", "request", ")", ":", "self", ".", "refresh_token", "=", "request", ".", "post_param", "(", "\"refresh_token\"", ")", "if", "self", ".", "refresh_token", "is", "None", ":", "raise", "OAuthInvalidError", "(", "err...
Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError`
[ "Validate", "the", "incoming", "request", "." ]
train
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L973-L1015
fictorial/pygameui
pygameui/kvc.py
value_for_keypath
def value_for_keypath(obj, path): """Get value from walking key path with start object obj. """ val = obj for part in path.split('.'): match = re.match(list_index_re, part) if match is not None: val = _extract(val, match.group(1)) if not isinstance(val, list) and not isinstance(val, tuple): raise TypeError('expected list/tuple') index = int(match.group(2)) val = val[index] else: val = _extract(val, part) if val is None: return None return val
python
def value_for_keypath(obj, path): """Get value from walking key path with start object obj. """ val = obj for part in path.split('.'): match = re.match(list_index_re, part) if match is not None: val = _extract(val, match.group(1)) if not isinstance(val, list) and not isinstance(val, tuple): raise TypeError('expected list/tuple') index = int(match.group(2)) val = val[index] else: val = _extract(val, part) if val is None: return None return val
[ "def", "value_for_keypath", "(", "obj", ",", "path", ")", ":", "val", "=", "obj", "for", "part", "in", "path", ".", "split", "(", "'.'", ")", ":", "match", "=", "re", ".", "match", "(", "list_index_re", ",", "part", ")", "if", "match", "is", "not",...
Get value from walking key path with start object obj.
[ "Get", "value", "from", "walking", "key", "path", "with", "start", "object", "obj", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/kvc.py#L58-L74
fictorial/pygameui
pygameui/kvc.py
set_value_for_keypath
def set_value_for_keypath(obj, path, new_value, preserve_child = False): """Set attribute value new_value at key path of start object obj. """ parts = path.split('.') last_part = len(parts) - 1 dst = obj for i, part in enumerate(parts): match = re.match(list_index_re, part) if match is not None: dst = _extract(dst, match.group(1)) if not isinstance(dst, list) and not isinstance(dst, tuple): raise TypeError('expected list/tuple') index = int(match.group(2)) if i == last_part: dst[index] = new_value else: dst = dst[index] else: if i != last_part: dst = _extract(dst, part) else: if isinstance(dst, dict): dst[part] = new_value else: if not preserve_child: setattr(dst, part, new_value) else: try: v = getattr(dst, part) except AttributeError: setattr(dst, part, new_value)
python
def set_value_for_keypath(obj, path, new_value, preserve_child = False): """Set attribute value new_value at key path of start object obj. """ parts = path.split('.') last_part = len(parts) - 1 dst = obj for i, part in enumerate(parts): match = re.match(list_index_re, part) if match is not None: dst = _extract(dst, match.group(1)) if not isinstance(dst, list) and not isinstance(dst, tuple): raise TypeError('expected list/tuple') index = int(match.group(2)) if i == last_part: dst[index] = new_value else: dst = dst[index] else: if i != last_part: dst = _extract(dst, part) else: if isinstance(dst, dict): dst[part] = new_value else: if not preserve_child: setattr(dst, part, new_value) else: try: v = getattr(dst, part) except AttributeError: setattr(dst, part, new_value)
[ "def", "set_value_for_keypath", "(", "obj", ",", "path", ",", "new_value", ",", "preserve_child", "=", "False", ")", ":", "parts", "=", "path", ".", "split", "(", "'.'", ")", "last_part", "=", "len", "(", "parts", ")", "-", "1", "dst", "=", "obj", "f...
Set attribute value new_value at key path of start object obj.
[ "Set", "attribute", "value", "new_value", "at", "key", "path", "of", "start", "object", "obj", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/kvc.py#L77-L107
fictorial/pygameui
pygameui/imageview.py
view_for_image_named
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
python
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
[ "def", "view_for_image_named", "(", "image_name", ")", ":", "image", "=", "resource", ".", "get_image", "(", "image_name", ")", "if", "not", "image", ":", "return", "None", "return", "ImageView", "(", "pygame", ".", "Rect", "(", "0", ",", "0", ",", "0", ...
Create an ImageView for the given image.
[ "Create", "an", "ImageView", "for", "the", "given", "image", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/imageview.py#L64-L72
fictorial/pygameui
distribute_setup.py
main
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv))
python
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv))
[ "def", "main", "(", "argv", ",", "version", "=", "DEFAULT_VERSION", ")", ":", "tarball", "=", "download_setuptools", "(", ")", "_install", "(", "tarball", ",", "_build_install_args", "(", "argv", ")", ")" ]
Install or upgrade setuptools and EasyInstall
[ "Install", "or", "upgrade", "setuptools", "and", "EasyInstall" ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/distribute_setup.py#L487-L490
fictorial/pygameui
pygameui/render.py
fill_gradient
def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True): """Fill a surface with a linear gradient pattern. color starting color gradient final color rect area to fill; default is surface's rect vertical True=vertical; False=horizontal forward True=forward; False=reverse See http://www.pygame.org/wiki/GradientCode """ if rect is None: rect = surface.get_rect() x1, x2 = rect.left, rect.right y1, y2 = rect.top, rect.bottom if vertical: h = y2 - y1 else: h = x2 - x1 assert h > 0 if forward: a, b = color, gradient else: b, a = color, gradient rate = (float(b[0] - a[0]) / h, float(b[1] - a[1]) / h, float(b[2] - a[2]) / h) fn_line = pygame.draw.line if vertical: for line in range(y1, y2): color = (min(max(a[0] + (rate[0] * (line - y1)), 0), 255), min(max(a[1] + (rate[1] * (line - y1)), 0), 255), min(max(a[2] + (rate[2] * (line - y1)), 0), 255)) fn_line(surface, color, (x1, line), (x2, line)) else: for col in range(x1, x2): color = (min(max(a[0] + (rate[0] * (col - x1)), 0), 255), min(max(a[1] + (rate[1] * (col - x1)), 0), 255), min(max(a[2] + (rate[2] * (col - x1)), 0), 255)) fn_line(surface, color, (col, y1), (col, y2))
python
def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True): """Fill a surface with a linear gradient pattern. color starting color gradient final color rect area to fill; default is surface's rect vertical True=vertical; False=horizontal forward True=forward; False=reverse See http://www.pygame.org/wiki/GradientCode """ if rect is None: rect = surface.get_rect() x1, x2 = rect.left, rect.right y1, y2 = rect.top, rect.bottom if vertical: h = y2 - y1 else: h = x2 - x1 assert h > 0 if forward: a, b = color, gradient else: b, a = color, gradient rate = (float(b[0] - a[0]) / h, float(b[1] - a[1]) / h, float(b[2] - a[2]) / h) fn_line = pygame.draw.line if vertical: for line in range(y1, y2): color = (min(max(a[0] + (rate[0] * (line - y1)), 0), 255), min(max(a[1] + (rate[1] * (line - y1)), 0), 255), min(max(a[2] + (rate[2] * (line - y1)), 0), 255)) fn_line(surface, color, (x1, line), (x2, line)) else: for col in range(x1, x2): color = (min(max(a[0] + (rate[0] * (col - x1)), 0), 255), min(max(a[1] + (rate[1] * (col - x1)), 0), 255), min(max(a[2] + (rate[2] * (col - x1)), 0), 255)) fn_line(surface, color, (col, y1), (col, y2))
[ "def", "fill_gradient", "(", "surface", ",", "color", ",", "gradient", ",", "rect", "=", "None", ",", "vertical", "=", "True", ",", "forward", "=", "True", ")", ":", "if", "rect", "is", "None", ":", "rect", "=", "surface", ".", "get_rect", "(", ")", ...
Fill a surface with a linear gradient pattern. color starting color gradient final color rect area to fill; default is surface's rect vertical True=vertical; False=horizontal forward True=forward; False=reverse See http://www.pygame.org/wiki/GradientCode
[ "Fill", "a", "surface", "with", "a", "linear", "gradient", "pattern", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/render.py#L4-L66
fictorial/pygameui
pygameui/label.py
Label.shrink_wrap
def shrink_wrap(self): """Tightly bound the current text respecting current padding.""" self.frame.size = (self.text_size[0] + self.padding[0] * 2, self.text_size[1] + self.padding[1] * 2)
python
def shrink_wrap(self): """Tightly bound the current text respecting current padding.""" self.frame.size = (self.text_size[0] + self.padding[0] * 2, self.text_size[1] + self.padding[1] * 2)
[ "def", "shrink_wrap", "(", "self", ")", ":", "self", ".", "frame", ".", "size", "=", "(", "self", ".", "text_size", "[", "0", "]", "+", "self", ".", "padding", "[", "0", "]", "*", "2", ",", "self", ".", "text_size", "[", "1", "]", "+", "self", ...
Tightly bound the current text respecting current padding.
[ "Tightly", "bound", "the", "current", "text", "respecting", "current", "padding", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/label.py#L187-L191
fictorial/pygameui
pygameui/view.py
View.layout
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame.Surface( shadowed_frame_size, pygame.SRCALPHA, 32) shadow_image = resource.get_image('shadow') self.shadow_image = resource.scale_image(shadow_image, shadowed_frame_size) else: self.surface = pygame.Surface(self.frame.size, pygame.SRCALPHA, 32) self.shadow_image = None
python
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame.Surface( shadowed_frame_size, pygame.SRCALPHA, 32) shadow_image = resource.get_image('shadow') self.shadow_image = resource.scale_image(shadow_image, shadowed_frame_size) else: self.surface = pygame.Surface(self.frame.size, pygame.SRCALPHA, 32) self.shadow_image = None
[ "def", "layout", "(", "self", ")", ":", "if", "self", ".", "shadowed", ":", "shadow_size", "=", "theme", ".", "current", ".", "shadow_size", "shadowed_frame_size", "=", "(", "self", ".", "frame", ".", "w", "+", "shadow_size", ",", "self", ".", "frame", ...
Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame.
[ "Call", "to", "have", "the", "view", "layout", "itself", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L74-L91
fictorial/pygameui
pygameui/view.py
View.stylize
def stylize(self): """Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled. """ # do children first in case parent needs to override their style for child in self.children: child.stylize() style = theme.current.get_dict(self) preserve_child = False try: preserve_child = getattr(theme.current, 'preserve_child') except: preserve_child = False for key, val in style.iteritems(): kvc.set_value_for_keypath(self, key, val, preserve_child) self.layout()
python
def stylize(self): """Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled. """ # do children first in case parent needs to override their style for child in self.children: child.stylize() style = theme.current.get_dict(self) preserve_child = False try: preserve_child = getattr(theme.current, 'preserve_child') except: preserve_child = False for key, val in style.iteritems(): kvc.set_value_for_keypath(self, key, val, preserve_child) self.layout()
[ "def", "stylize", "(", "self", ")", ":", "# do children first in case parent needs to override their style", "for", "child", "in", "self", ".", "children", ":", "child", ".", "stylize", "(", ")", "style", "=", "theme", ".", "current", ".", "get_dict", "(", "self...
Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled.
[ "Apply", "theme", "style", "attributes", "to", "this", "instance", "and", "its", "children", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L209-L227
fictorial/pygameui
pygameui/view.py
View.draw
def draw(self): """Do not call directly.""" if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children: if not child.hidden: child.draw() topleft = child.frame.topleft if child.shadowed: shadow_size = theme.current.shadow_size shadow_topleft = (topleft[0] - shadow_size // 2, topleft[1] - shadow_size // 2) self.surface.blit(child.shadow_image, shadow_topleft) self.surface.blit(child.surface, topleft) if child.border_color and child.border_widths is not None: if (type(child.border_widths) is int and child.border_widths > 0): pygame.draw.rect(self.surface, child.border_color, child.frame, child.border_widths) else: tw, lw, bw, rw = child.get_border_widths() tl = (child.frame.left, child.frame.top) tr = (child.frame.right - 1, child.frame.top) bl = (child.frame.left, child.frame.bottom - 1) br = (child.frame.right - 1, child.frame.bottom - 1) if tw > 0: pygame.draw.line(self.surface, child.border_color, tl, tr, tw) if lw > 0: pygame.draw.line(self.surface, child.border_color, tl, bl, lw) if bw > 0: pygame.draw.line(self.surface, child.border_color, bl, br, bw) if rw > 0: pygame.draw.line(self.surface, child.border_color, tr, br, rw) return True
python
def draw(self): """Do not call directly.""" if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children: if not child.hidden: child.draw() topleft = child.frame.topleft if child.shadowed: shadow_size = theme.current.shadow_size shadow_topleft = (topleft[0] - shadow_size // 2, topleft[1] - shadow_size // 2) self.surface.blit(child.shadow_image, shadow_topleft) self.surface.blit(child.surface, topleft) if child.border_color and child.border_widths is not None: if (type(child.border_widths) is int and child.border_widths > 0): pygame.draw.rect(self.surface, child.border_color, child.frame, child.border_widths) else: tw, lw, bw, rw = child.get_border_widths() tl = (child.frame.left, child.frame.top) tr = (child.frame.right - 1, child.frame.top) bl = (child.frame.left, child.frame.bottom - 1) br = (child.frame.right - 1, child.frame.bottom - 1) if tw > 0: pygame.draw.line(self.surface, child.border_color, tl, tr, tw) if lw > 0: pygame.draw.line(self.surface, child.border_color, tl, bl, lw) if bw > 0: pygame.draw.line(self.surface, child.border_color, bl, br, bw) if rw > 0: pygame.draw.line(self.surface, child.border_color, tr, br, rw) return True
[ "def", "draw", "(", "self", ")", ":", "if", "self", ".", "hidden", ":", "return", "False", "if", "self", ".", "background_color", "is", "not", "None", ":", "render", ".", "fillrect", "(", "self", ".", "surface", ",", "self", ".", "background_color", ",...
Do not call directly.
[ "Do", "not", "call", "directly", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L229-L278
fictorial/pygameui
pygameui/view.py
View.get_border_widths
def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths
python
def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths
[ "def", "get_border_widths", "(", "self", ")", ":", "if", "type", "(", "self", ".", "border_widths", ")", "is", "int", ":", "# uniform size", "return", "[", "self", ".", "border_widths", "]", "*", "4", "return", "self", ".", "border_widths" ]
Return border width for each side top, left, bottom, right.
[ "Return", "border", "width", "for", "each", "side", "top", "left", "bottom", "right", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L280-L284
fictorial/pygameui
pygameui/view.py
View.hit
def hit(self, pt): """Find the view (self, child, or None) under the point `pt`.""" if self.hidden or not self._enabled: return None if not self.frame.collidepoint(pt): return None local_pt = (pt[0] - self.frame.topleft[0], pt[1] - self.frame.topleft[1]) for child in reversed(self.children): # front to back hit_view = child.hit(local_pt) if hit_view is not None: return hit_view return self
python
def hit(self, pt): """Find the view (self, child, or None) under the point `pt`.""" if self.hidden or not self._enabled: return None if not self.frame.collidepoint(pt): return None local_pt = (pt[0] - self.frame.topleft[0], pt[1] - self.frame.topleft[1]) for child in reversed(self.children): # front to back hit_view = child.hit(local_pt) if hit_view is not None: return hit_view return self
[ "def", "hit", "(", "self", ",", "pt", ")", ":", "if", "self", ".", "hidden", "or", "not", "self", ".", "_enabled", ":", "return", "None", "if", "not", "self", ".", "frame", ".", "collidepoint", "(", "pt", ")", ":", "return", "None", "local_pt", "="...
Find the view (self, child, or None) under the point `pt`.
[ "Find", "the", "view", "(", "self", "child", "or", "None", ")", "under", "the", "point", "pt", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L286-L303
fictorial/pygameui
pygameui/view.py
View.bring_to_front
def bring_to_front(self): """TODO: explain depth sorting""" if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[-1], ch[index] = ch[index], ch[-1]
python
def bring_to_front(self): """TODO: explain depth sorting""" if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[-1], ch[index] = ch[index], ch[-1]
[ "def", "bring_to_front", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "ch", "=", "self", ".", "parent", ".", "children", "index", "=", "ch", ".", "index", "(", "self", ")", "ch", "[", "-", "1", "]", ",", "ch", "...
TODO: explain depth sorting
[ "TODO", ":", "explain", "depth", "sorting" ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L347-L352
fictorial/pygameui
pygameui/theme.py
use_theme
def use_theme(theme): """Make the given theme current. There are two included themes: light_theme, dark_theme. """ global current current = theme import scene if scene.current is not None: scene.current.stylize()
python
def use_theme(theme): """Make the given theme current. There are two included themes: light_theme, dark_theme. """ global current current = theme import scene if scene.current is not None: scene.current.stylize()
[ "def", "use_theme", "(", "theme", ")", ":", "global", "current", "current", "=", "theme", "import", "scene", "if", "scene", ".", "current", "is", "not", "None", ":", "scene", ".", "current", ".", "stylize", "(", ")" ]
Make the given theme current. There are two included themes: light_theme, dark_theme.
[ "Make", "the", "given", "theme", "current", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L176-L185
fictorial/pygameui
pygameui/theme.py
Theme.set
def set(self, class_name, state, key, value): """Set a single style value for a view class and state. class_name The name of the class to be styled; do not include the package name; e.g. 'Button'. state The name of the state to be stylized. One of the following: 'normal', 'focused', 'selected', 'disabled' is common. key The style attribute name; e.g. 'background_color'. value The value of the style attribute; colors are either a 3-tuple for RGB, a 4-tuple for RGBA, or a pair thereof for a linear gradient. """ self._styles.setdefault(class_name, {}).setdefault(state, {}) self._styles[class_name][state][key] = value
python
def set(self, class_name, state, key, value): """Set a single style value for a view class and state. class_name The name of the class to be styled; do not include the package name; e.g. 'Button'. state The name of the state to be stylized. One of the following: 'normal', 'focused', 'selected', 'disabled' is common. key The style attribute name; e.g. 'background_color'. value The value of the style attribute; colors are either a 3-tuple for RGB, a 4-tuple for RGBA, or a pair thereof for a linear gradient. """ self._styles.setdefault(class_name, {}).setdefault(state, {}) self._styles[class_name][state][key] = value
[ "def", "set", "(", "self", ",", "class_name", ",", "state", ",", "key", ",", "value", ")", ":", "self", ".", "_styles", ".", "setdefault", "(", "class_name", ",", "{", "}", ")", ".", "setdefault", "(", "state", ",", "{", "}", ")", "self", ".", "_...
Set a single style value for a view class and state. class_name The name of the class to be styled; do not include the package name; e.g. 'Button'. state The name of the state to be stylized. One of the following: 'normal', 'focused', 'selected', 'disabled' is common. key The style attribute name; e.g. 'background_color'. value The value of the style attribute; colors are either a 3-tuple for RGB, a 4-tuple for RGBA, or a pair thereof for a linear gradient.
[ "Set", "a", "single", "style", "value", "for", "a", "view", "class", "and", "state", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L71-L97
fictorial/pygameui
pygameui/theme.py
Theme.get_dict_for_class
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attribute of the view instance is taken as the current state if state is None. If the state is not 'normal' then the style definitions for the 'normal' state are mixed-in from the given state style definitions, giving precedence to the non-'normal' style definitions. """ classes = [] klass = class_name while True: classes.append(klass) if klass.__name__ == base_name: break klass = klass.__bases__[0] if state is None: state = 'normal' style = {} for klass in classes: class_name = klass.__name__ try: state_styles = self._styles[class_name][state] except KeyError: state_styles = {} if state != 'normal': try: normal_styles = self._styles[class_name]['normal'] except KeyError: normal_styles = {} state_styles = dict(chain(normal_styles.iteritems(), state_styles.iteritems())) style = dict(chain(state_styles.iteritems(), style.iteritems())) return style
python
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attribute of the view instance is taken as the current state if state is None. If the state is not 'normal' then the style definitions for the 'normal' state are mixed-in from the given state style definitions, giving precedence to the non-'normal' style definitions. """ classes = [] klass = class_name while True: classes.append(klass) if klass.__name__ == base_name: break klass = klass.__bases__[0] if state is None: state = 'normal' style = {} for klass in classes: class_name = klass.__name__ try: state_styles = self._styles[class_name][state] except KeyError: state_styles = {} if state != 'normal': try: normal_styles = self._styles[class_name]['normal'] except KeyError: normal_styles = {} state_styles = dict(chain(normal_styles.iteritems(), state_styles.iteritems())) style = dict(chain(state_styles.iteritems(), style.iteritems())) return style
[ "def", "get_dict_for_class", "(", "self", ",", "class_name", ",", "state", "=", "None", ",", "base_name", "=", "'View'", ")", ":", "classes", "=", "[", "]", "klass", "=", "class_name", "while", "True", ":", "classes", ".", "append", "(", "klass", ")", ...
The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attribute of the view instance is taken as the current state if state is None. If the state is not 'normal' then the style definitions for the 'normal' state are mixed-in from the given state style definitions, giving precedence to the non-'normal' style definitions.
[ "The", "style", "dict", "for", "a", "given", "class", "and", "state", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L99-L149
fictorial/pygameui
pygameui/theme.py
Theme.get_dict
def get_dict(self, obj, state=None, base_name='View'): """The style dict for a view instance. """ return self.get_dict_for_class(class_name=obj.__class__, state=obj.state, base_name=base_name)
python
def get_dict(self, obj, state=None, base_name='View'): """The style dict for a view instance. """ return self.get_dict_for_class(class_name=obj.__class__, state=obj.state, base_name=base_name)
[ "def", "get_dict", "(", "self", ",", "obj", ",", "state", "=", "None", ",", "base_name", "=", "'View'", ")", ":", "return", "self", ".", "get_dict_for_class", "(", "class_name", "=", "obj", ".", "__class__", ",", "state", "=", "obj", ".", "state", ",",...
The style dict for a view instance.
[ "The", "style", "dict", "for", "a", "view", "instance", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L151-L157
fictorial/pygameui
pygameui/theme.py
Theme.get_value
def get_value(self, class_name, attr, default_value=None, state='normal', base_name='View'): """Get a single style attribute value for the given class. """ styles = self.get_dict_for_class(class_name, state, base_name) try: return styles[attr] except KeyError: return default_value
python
def get_value(self, class_name, attr, default_value=None, state='normal', base_name='View'): """Get a single style attribute value for the given class. """ styles = self.get_dict_for_class(class_name, state, base_name) try: return styles[attr] except KeyError: return default_value
[ "def", "get_value", "(", "self", ",", "class_name", ",", "attr", ",", "default_value", "=", "None", ",", "state", "=", "'normal'", ",", "base_name", "=", "'View'", ")", ":", "styles", "=", "self", ".", "get_dict_for_class", "(", "class_name", ",", "state",...
Get a single style attribute value for the given class.
[ "Get", "a", "single", "style", "attribute", "value", "for", "the", "given", "class", "." ]
train
https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L159-L168
grantmcconnaughey/django-field-history
field_history/json_nested_serializer.py
Serializer.serialize
def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", six.StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) if self.use_natural_keys and RemovedInDjango19Warning is not None: warnings.warn("``use_natural_keys`` is deprecated; use ``use_natural_foreign_keys`` instead.", RemovedInDjango19Warning) self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False) or self.use_natural_keys self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False) self.start_serialization() self.first = True for obj in queryset: self.start_object(obj) # Use the concrete parent class' _meta instead of the object's _meta # This is to avoid local_fields problems for proxy models. Refs #17717. concrete_model = obj._meta.concrete_model # only one change local_fields -> fields for supporting nested models for field in concrete_model._meta.fields: if field.serialize: if field.remote_field is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_field(obj, field) else: if self.selected_fields is None or field.attname[:-3] in self.selected_fields: self.handle_fk_field(obj, field) for field in concrete_model._meta.many_to_many: if field.serialize: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_m2m_field(obj, field) self.end_object(obj) if self.first: self.first = False self.end_serialization() return self.getvalue()
python
def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", six.StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) if self.use_natural_keys and RemovedInDjango19Warning is not None: warnings.warn("``use_natural_keys`` is deprecated; use ``use_natural_foreign_keys`` instead.", RemovedInDjango19Warning) self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False) or self.use_natural_keys self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False) self.start_serialization() self.first = True for obj in queryset: self.start_object(obj) # Use the concrete parent class' _meta instead of the object's _meta # This is to avoid local_fields problems for proxy models. Refs #17717. concrete_model = obj._meta.concrete_model # only one change local_fields -> fields for supporting nested models for field in concrete_model._meta.fields: if field.serialize: if field.remote_field is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_field(obj, field) else: if self.selected_fields is None or field.attname[:-3] in self.selected_fields: self.handle_fk_field(obj, field) for field in concrete_model._meta.many_to_many: if field.serialize: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_m2m_field(obj, field) self.end_object(obj) if self.first: self.first = False self.end_serialization() return self.getvalue()
[ "def", "serialize", "(", "self", ",", "queryset", ",", "*", "*", "options", ")", ":", "self", ".", "options", "=", "options", "self", ".", "stream", "=", "options", ".", "pop", "(", "\"stream\"", ",", "six", ".", "StringIO", "(", ")", ")", "self", ...
Serialize a queryset.
[ "Serialize", "a", "queryset", "." ]
train
https://github.com/grantmcconnaughey/django-field-history/blob/b61885d8bddf7d1f53addf3bea098f67fcf9a618/field_history/json_nested_serializer.py#L26-L65
grantmcconnaughey/django-field-history
field_history/tracker.py
FieldInstanceTracker.current
def current(self, fields=None): """Returns dict of current values for all tracked fields""" if fields is None: fields = self.fields return dict((f, self.get_field_value(f)) for f in fields)
python
def current(self, fields=None): """Returns dict of current values for all tracked fields""" if fields is None: fields = self.fields return dict((f, self.get_field_value(f)) for f in fields)
[ "def", "current", "(", "self", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "fields", "=", "self", ".", "fields", "return", "dict", "(", "(", "f", ",", "self", ".", "get_field_value", "(", "f", ")", ")", "for", "f", "i...
Returns dict of current values for all tracked fields
[ "Returns", "dict", "of", "current", "values", "for", "all", "tracked", "fields" ]
train
https://github.com/grantmcconnaughey/django-field-history/blob/b61885d8bddf7d1f53addf3bea098f67fcf9a618/field_history/tracker.py#L36-L41
grantmcconnaughey/django-field-history
field_history/models.py
instantiate_object_id_field
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField): """ Instantiates and returns a model field for FieldHistory.object_id. object_id_class_or_tuple may be either a Django model field class or a tuple of (model_field, kwargs), where kwargs is a dict passed to model_field's constructor. """ if isinstance(object_id_class_or_tuple, (list, tuple)): object_id_class, object_id_kwargs = object_id_class_or_tuple else: object_id_class = object_id_class_or_tuple object_id_kwargs = {} if not issubclass(object_id_class, models.fields.Field): raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING) if not isinstance(object_id_kwargs, dict): raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING) return object_id_class(db_index=True, **object_id_kwargs)
python
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField): """ Instantiates and returns a model field for FieldHistory.object_id. object_id_class_or_tuple may be either a Django model field class or a tuple of (model_field, kwargs), where kwargs is a dict passed to model_field's constructor. """ if isinstance(object_id_class_or_tuple, (list, tuple)): object_id_class, object_id_kwargs = object_id_class_or_tuple else: object_id_class = object_id_class_or_tuple object_id_kwargs = {} if not issubclass(object_id_class, models.fields.Field): raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING) if not isinstance(object_id_kwargs, dict): raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING) return object_id_class(db_index=True, **object_id_kwargs)
[ "def", "instantiate_object_id_field", "(", "object_id_class_or_tuple", "=", "models", ".", "TextField", ")", ":", "if", "isinstance", "(", "object_id_class_or_tuple", ",", "(", "list", ",", "tuple", ")", ")", ":", "object_id_class", ",", "object_id_kwargs", "=", "...
Instantiates and returns a model field for FieldHistory.object_id. object_id_class_or_tuple may be either a Django model field class or a tuple of (model_field, kwargs), where kwargs is a dict passed to model_field's constructor.
[ "Instantiates", "and", "returns", "a", "model", "field", "for", "FieldHistory", ".", "object_id", "." ]
train
https://github.com/grantmcconnaughey/django-field-history/blob/b61885d8bddf7d1f53addf3bea098f67fcf9a618/field_history/models.py#L16-L35
mbr/flask-kvsession
flask_kvsession/__init__.py
SessionID.has_expired
def has_expired(self, lifetime, now=None): """Report if the session key has expired. :param lifetime: A :class:`datetime.timedelta` that specifies the maximum age this :class:`SessionID` should be checked against. :param now: If specified, use this :class:`~datetime.datetime` instance instead of :meth:`~datetime.datetime.utcnow()` as the current time. """ now = now or datetime.utcnow() return now > self.created + lifetime
python
def has_expired(self, lifetime, now=None): """Report if the session key has expired. :param lifetime: A :class:`datetime.timedelta` that specifies the maximum age this :class:`SessionID` should be checked against. :param now: If specified, use this :class:`~datetime.datetime` instance instead of :meth:`~datetime.datetime.utcnow()` as the current time. """ now = now or datetime.utcnow() return now > self.created + lifetime
[ "def", "has_expired", "(", "self", ",", "lifetime", ",", "now", "=", "None", ")", ":", "now", "=", "now", "or", "datetime", ".", "utcnow", "(", ")", "return", "now", ">", "self", ".", "created", "+", "lifetime" ]
Report if the session key has expired. :param lifetime: A :class:`datetime.timedelta` that specifies the maximum age this :class:`SessionID` should be checked against. :param now: If specified, use this :class:`~datetime.datetime` instance instead of :meth:`~datetime.datetime.utcnow()` as the current time.
[ "Report", "if", "the", "session", "key", "has", "expired", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L41-L52
mbr/flask-kvsession
flask_kvsession/__init__.py
SessionID.unserialize
def unserialize(cls, string): """Unserializes from a string. :param string: A string created by :meth:`serialize`. """ id_s, created_s = string.split('_') return cls(int(id_s, 16), datetime.utcfromtimestamp(int(created_s, 16)))
python
def unserialize(cls, string): """Unserializes from a string. :param string: A string created by :meth:`serialize`. """ id_s, created_s = string.split('_') return cls(int(id_s, 16), datetime.utcfromtimestamp(int(created_s, 16)))
[ "def", "unserialize", "(", "cls", ",", "string", ")", ":", "id_s", ",", "created_s", "=", "string", ".", "split", "(", "'_'", ")", "return", "cls", "(", "int", "(", "id_s", ",", "16", ")", ",", "datetime", ".", "utcfromtimestamp", "(", "int", "(", ...
Unserializes from a string. :param string: A string created by :meth:`serialize`.
[ "Unserializes", "from", "a", "string", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L60-L67
mbr/flask-kvsession
flask_kvsession/__init__.py
KVSession.destroy
def destroy(self): """Destroys a session completely, by deleting all keys and removing it from the internal store immediately. This allows removing a session for security reasons, e.g. a login stored in a session will cease to exist if the session is destroyed. """ for k in list(self.keys()): del self[k] if getattr(self, 'sid_s', None): current_app.kvsession_store.delete(self.sid_s) self.sid_s = None self.modified = False self.new = False
python
def destroy(self): """Destroys a session completely, by deleting all keys and removing it from the internal store immediately. This allows removing a session for security reasons, e.g. a login stored in a session will cease to exist if the session is destroyed. """ for k in list(self.keys()): del self[k] if getattr(self, 'sid_s', None): current_app.kvsession_store.delete(self.sid_s) self.sid_s = None self.modified = False self.new = False
[ "def", "destroy", "(", "self", ")", ":", "for", "k", "in", "list", "(", "self", ".", "keys", "(", ")", ")", ":", "del", "self", "[", "k", "]", "if", "getattr", "(", "self", ",", "'sid_s'", ",", "None", ")", ":", "current_app", ".", "kvsession_sto...
Destroys a session completely, by deleting all keys and removing it from the internal store immediately. This allows removing a session for security reasons, e.g. a login stored in a session will cease to exist if the session is destroyed.
[ "Destroys", "a", "session", "completely", "by", "deleting", "all", "keys", "and", "removing", "it", "from", "the", "internal", "store", "immediately", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L89-L104
mbr/flask-kvsession
flask_kvsession/__init__.py
KVSession.regenerate
def regenerate(self): """Generate a new session id for this session. To avoid vulnerabilities through `session fixation attacks <http://en.wikipedia.org/wiki/Session_fixation>`_, this function can be called after an action like a login has taken place. The session will be copied over to a new session id and the old one removed. """ self.modified = True if getattr(self, 'sid_s', None): # delete old session current_app.kvsession_store.delete(self.sid_s) # remove sid_s, set modified self.sid_s = None self.modified = True
python
def regenerate(self): """Generate a new session id for this session. To avoid vulnerabilities through `session fixation attacks <http://en.wikipedia.org/wiki/Session_fixation>`_, this function can be called after an action like a login has taken place. The session will be copied over to a new session id and the old one removed. """ self.modified = True if getattr(self, 'sid_s', None): # delete old session current_app.kvsession_store.delete(self.sid_s) # remove sid_s, set modified self.sid_s = None self.modified = True
[ "def", "regenerate", "(", "self", ")", ":", "self", ".", "modified", "=", "True", "if", "getattr", "(", "self", ",", "'sid_s'", ",", "None", ")", ":", "# delete old session", "current_app", ".", "kvsession_store", ".", "delete", "(", "self", ".", "sid_s", ...
Generate a new session id for this session. To avoid vulnerabilities through `session fixation attacks <http://en.wikipedia.org/wiki/Session_fixation>`_, this function can be called after an action like a login has taken place. The session will be copied over to a new session id and the old one removed.
[ "Generate", "a", "new", "session", "id", "for", "this", "session", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L106-L122
mbr/flask-kvsession
flask_kvsession/__init__.py
KVSessionExtension.cleanup_sessions
def cleanup_sessions(self, app=None): """Removes all expired session from the store. Periodically, this function can be called to remove sessions from the backend store that have expired, as they are not removed automatically unless the backend supports time-to-live and has been configured appropriately (see :class:`~simplekv.TimeToLiveMixin`). This function retrieves all session keys, checks they are older than :attr:`flask.Flask.permanent_session_lifetime` and if so, removes them. Note that no distinction is made between non-permanent and permanent sessions. :param app: The app whose sessions should be cleaned up. If ``None``, uses :py:data:`~flask.current_app`.""" if not app: app = current_app for key in app.kvsession_store.keys(): m = self.key_regex.match(key) now = datetime.utcnow() if m: # read id sid = SessionID.unserialize(key) # remove if expired if sid.has_expired(app.permanent_session_lifetime, now): app.kvsession_store.delete(key)
python
def cleanup_sessions(self, app=None): """Removes all expired session from the store. Periodically, this function can be called to remove sessions from the backend store that have expired, as they are not removed automatically unless the backend supports time-to-live and has been configured appropriately (see :class:`~simplekv.TimeToLiveMixin`). This function retrieves all session keys, checks they are older than :attr:`flask.Flask.permanent_session_lifetime` and if so, removes them. Note that no distinction is made between non-permanent and permanent sessions. :param app: The app whose sessions should be cleaned up. If ``None``, uses :py:data:`~flask.current_app`.""" if not app: app = current_app for key in app.kvsession_store.keys(): m = self.key_regex.match(key) now = datetime.utcnow() if m: # read id sid = SessionID.unserialize(key) # remove if expired if sid.has_expired(app.permanent_session_lifetime, now): app.kvsession_store.delete(key)
[ "def", "cleanup_sessions", "(", "self", ",", "app", "=", "None", ")", ":", "if", "not", "app", ":", "app", "=", "current_app", "for", "key", "in", "app", ".", "kvsession_store", ".", "keys", "(", ")", ":", "m", "=", "self", ".", "key_regex", ".", "...
Removes all expired session from the store. Periodically, this function can be called to remove sessions from the backend store that have expired, as they are not removed automatically unless the backend supports time-to-live and has been configured appropriately (see :class:`~simplekv.TimeToLiveMixin`). This function retrieves all session keys, checks they are older than :attr:`flask.Flask.permanent_session_lifetime` and if so, removes them. Note that no distinction is made between non-permanent and permanent sessions. :param app: The app whose sessions should be cleaned up. If ``None``, uses :py:data:`~flask.current_app`.
[ "Removes", "all", "expired", "session", "from", "the", "store", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L222-L250
mbr/flask-kvsession
flask_kvsession/__init__.py
KVSessionExtension.init_app
def init_app(self, app, session_kvstore=None): """Initialize application and KVSession. This will replace the session management of the application with Flask-KVSession's. :param app: The :class:`~flask.Flask` app to be initialized.""" app.config.setdefault('SESSION_KEY_BITS', 64) app.config.setdefault('SESSION_RANDOM_SOURCE', SystemRandom()) if not session_kvstore and not self.default_kvstore: raise ValueError('Must supply session_kvstore either on ' 'construction or init_app().') # set store on app, either use default # or supplied argument app.kvsession_store = session_kvstore or self.default_kvstore app.session_interface = KVSessionInterface()
python
def init_app(self, app, session_kvstore=None): """Initialize application and KVSession. This will replace the session management of the application with Flask-KVSession's. :param app: The :class:`~flask.Flask` app to be initialized.""" app.config.setdefault('SESSION_KEY_BITS', 64) app.config.setdefault('SESSION_RANDOM_SOURCE', SystemRandom()) if not session_kvstore and not self.default_kvstore: raise ValueError('Must supply session_kvstore either on ' 'construction or init_app().') # set store on app, either use default # or supplied argument app.kvsession_store = session_kvstore or self.default_kvstore app.session_interface = KVSessionInterface()
[ "def", "init_app", "(", "self", ",", "app", ",", "session_kvstore", "=", "None", ")", ":", "app", ".", "config", ".", "setdefault", "(", "'SESSION_KEY_BITS'", ",", "64", ")", "app", ".", "config", ".", "setdefault", "(", "'SESSION_RANDOM_SOURCE'", ",", "Sy...
Initialize application and KVSession. This will replace the session management of the application with Flask-KVSession's. :param app: The :class:`~flask.Flask` app to be initialized.
[ "Initialize", "application", "and", "KVSession", "." ]
train
https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L252-L270
python-fedex-devs/python-fedex
label_certification/cert_config.py
transfer_config_dict
def transfer_config_dict(soap_object, data_dict): """ This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script. """ for key, val in data_dict.items(): # Transfer each key to the matching attribute ont he SOAP object. setattr(soap_object, key, val)
python
def transfer_config_dict(soap_object, data_dict): """ This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script. """ for key, val in data_dict.items(): # Transfer each key to the matching attribute ont he SOAP object. setattr(soap_object, key, val)
[ "def", "transfer_config_dict", "(", "soap_object", ",", "data_dict", ")", ":", "for", "key", ",", "val", "in", "data_dict", ".", "items", "(", ")", ":", "# Transfer each key to the matching attribute ont he SOAP object.", "setattr", "(", "soap_object", ",", "key", "...
This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script.
[ "This", "is", "a", "utility", "function", "used", "in", "the", "certification", "modules", "to", "transfer", "the", "data", "dicts", "above", "to", "SOAP", "objects", ".", "This", "avoids", "repetition", "and", "allows", "us", "to", "store", "all", "of", "...
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/label_certification/cert_config.py#L65-L74
python-fedex-devs/python-fedex
fedex/services/pickup_service.py
FedexCreatePickupRequest._assemble_and_send_request
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.createPickup( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, OriginDetail=self.OriginDetail, PickupServiceCategory=self.PickupServiceCategory, PackageCount=self.PackageCount, TotalWeight=self.TotalWeight, CarrierCode=self.CarrierCode, OversizePackageCount=self.OversizePackageCount, Remarks=self.Remarks, CommodityDescription=self.CommodityDescription, CountryRelationship=self.CountryRelationship )
python
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.createPickup( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, OriginDetail=self.OriginDetail, PickupServiceCategory=self.PickupServiceCategory, PackageCount=self.PackageCount, TotalWeight=self.TotalWeight, CarrierCode=self.CarrierCode, OversizePackageCount=self.OversizePackageCount, Remarks=self.Remarks, CommodityDescription=self.CommodityDescription, CountryRelationship=self.CountryRelationship )
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "createPickup", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=", "self", ...
Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/pickup_service.py#L43-L66
python-fedex-devs/python-fedex
fedex/services/pickup_service.py
FedexPickupAvailabilityRequest._assemble_and_send_request
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.getPickupAvailability( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, PickupType=self.PickupType, AccountNumber=self.AccountNumber, PickupAddress=self.PickupAddress, PickupRequestType=self.PickupRequestType, DispatchDate=self.DispatchDate, NumberOfBusinessDays=self.NumberOfBusinessDays, PackageReadyTime=self.PackageReadyTime, CustomerCloseTime=self.CustomerCloseTime, Carriers=self.Carriers, ShipmentAttributes=self.ShipmentAttributes, PackageDetails=self.PackageDetails )
python
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.getPickupAvailability( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, PickupType=self.PickupType, AccountNumber=self.AccountNumber, PickupAddress=self.PickupAddress, PickupRequestType=self.PickupRequestType, DispatchDate=self.DispatchDate, NumberOfBusinessDays=self.NumberOfBusinessDays, PackageReadyTime=self.PackageReadyTime, CustomerCloseTime=self.CustomerCloseTime, Carriers=self.Carriers, ShipmentAttributes=self.ShipmentAttributes, PackageDetails=self.PackageDetails )
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "getPickupAvailability", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=", "...
Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/pickup_service.py#L120-L145
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexProcessShipmentRequest._prepare_wsdl_objects
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ # This is the primary data structure for processShipment requests. self.RequestedShipment = self.client.factory.create('RequestedShipment') self.RequestedShipment.ShipTimestamp = datetime.datetime.now() # Defaults for TotalWeight wsdl object. total_weight = self.client.factory.create('Weight') # Start at nothing. total_weight.Value = 0.0 # Default to pounds. total_weight.Units = 'LB' # This is the total weight of the entire shipment. Shipments may # contain more than one package. self.RequestedShipment.TotalWeight = total_weight # This is the top level data structure Shipper Party information. shipper_party = self.client.factory.create('Party') shipper_party.Address = self.client.factory.create('Address') shipper_party.Contact = self.client.factory.create('Contact') # Link the Shipper Party to our master data structure. self.RequestedShipment.Shipper = shipper_party # This is the top level data structure for RecipientParty information. recipient_party = self.client.factory.create('Party') recipient_party.Contact = self.client.factory.create('Contact') recipient_party.Address = self.client.factory.create('Address') # Link the RecipientParty object to our master data structure. self.RequestedShipment.Recipient = recipient_party payor = self.client.factory.create('Payor') # Grab the account number from the FedexConfig object by default. # Assume US. payor.ResponsibleParty = self.client.factory.create('Party') payor.ResponsibleParty.Address = self.client.factory.create('Address') payor.ResponsibleParty.Address.CountryCode = 'US' # ShippingChargesPayment WSDL object default values. shipping_charges_payment = self.client.factory.create('Payment') shipping_charges_payment.Payor = payor shipping_charges_payment.PaymentType = 'SENDER' self.RequestedShipment.ShippingChargesPayment = shipping_charges_payment self.RequestedShipment.LabelSpecification = self.client.factory.create('LabelSpecification') # NONE, PREFERRED or LIST self.RequestedShipment.RateRequestTypes = ['PREFERRED'] # Start with no packages, user must add them. self.RequestedShipment.PackageCount = 0 self.RequestedShipment.RequestedPackageLineItems = [] # This is good to review if you'd like to see what the data structure # looks like. self.logger.debug(self.RequestedShipment)
python
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ # This is the primary data structure for processShipment requests. self.RequestedShipment = self.client.factory.create('RequestedShipment') self.RequestedShipment.ShipTimestamp = datetime.datetime.now() # Defaults for TotalWeight wsdl object. total_weight = self.client.factory.create('Weight') # Start at nothing. total_weight.Value = 0.0 # Default to pounds. total_weight.Units = 'LB' # This is the total weight of the entire shipment. Shipments may # contain more than one package. self.RequestedShipment.TotalWeight = total_weight # This is the top level data structure Shipper Party information. shipper_party = self.client.factory.create('Party') shipper_party.Address = self.client.factory.create('Address') shipper_party.Contact = self.client.factory.create('Contact') # Link the Shipper Party to our master data structure. self.RequestedShipment.Shipper = shipper_party # This is the top level data structure for RecipientParty information. recipient_party = self.client.factory.create('Party') recipient_party.Contact = self.client.factory.create('Contact') recipient_party.Address = self.client.factory.create('Address') # Link the RecipientParty object to our master data structure. self.RequestedShipment.Recipient = recipient_party payor = self.client.factory.create('Payor') # Grab the account number from the FedexConfig object by default. # Assume US. payor.ResponsibleParty = self.client.factory.create('Party') payor.ResponsibleParty.Address = self.client.factory.create('Address') payor.ResponsibleParty.Address.CountryCode = 'US' # ShippingChargesPayment WSDL object default values. shipping_charges_payment = self.client.factory.create('Payment') shipping_charges_payment.Payor = payor shipping_charges_payment.PaymentType = 'SENDER' self.RequestedShipment.ShippingChargesPayment = shipping_charges_payment self.RequestedShipment.LabelSpecification = self.client.factory.create('LabelSpecification') # NONE, PREFERRED or LIST self.RequestedShipment.RateRequestTypes = ['PREFERRED'] # Start with no packages, user must add them. self.RequestedShipment.PackageCount = 0 self.RequestedShipment.RequestedPackageLineItems = [] # This is good to review if you'd like to see what the data structure # looks like. self.logger.debug(self.RequestedShipment)
[ "def", "_prepare_wsdl_objects", "(", "self", ")", ":", "# This is the primary data structure for processShipment requests.", "self", ".", "RequestedShipment", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'RequestedShipment'", ")", "self", ".", "Reque...
This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request.
[ "This", "is", "the", "data", "that", "will", "be", "used", "to", "create", "your", "shipment", ".", "Create", "the", "data", "structure", "and", "get", "it", "ready", "for", "the", "WSDL", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L44-L104
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexProcessShipmentRequest._assemble_and_send_validation_request
def _assemble_and_send_validation_request(self): """ Fires off the Fedex shipment validation request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_validation_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.validateShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, RequestedShipment=self.RequestedShipment)
python
def _assemble_and_send_validation_request(self): """ Fires off the Fedex shipment validation request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_validation_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.validateShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, RequestedShipment=self.RequestedShipment)
[ "def", "_assemble_and_send_validation_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "validateShipment", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=...
Fires off the Fedex shipment validation request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_validation_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "shipment", "validation", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L116-L131
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexProcessShipmentRequest._assemble_and_send_request
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.processShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, RequestedShipment=self.RequestedShipment)
python
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.processShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, RequestedShipment=self.RequestedShipment)
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "processShipment", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=", "self",...
Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L133-L147
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexProcessShipmentRequest.add_package
def add_package(self, package_item): """ Adds a package to the ship request. @type package_item: WSDL object, type of RequestedPackageLineItem WSDL object. @keyword package_item: A RequestedPackageLineItem, created by calling create_wsdl_object_of_type('RequestedPackageLineItem') on this ShipmentRequest object. See examples/create_shipment.py for more details. """ self.RequestedShipment.RequestedPackageLineItems.append(package_item) package_weight = package_item.Weight.Value self.RequestedShipment.TotalWeight.Value += package_weight self.RequestedShipment.PackageCount += 1
python
def add_package(self, package_item): """ Adds a package to the ship request. @type package_item: WSDL object, type of RequestedPackageLineItem WSDL object. @keyword package_item: A RequestedPackageLineItem, created by calling create_wsdl_object_of_type('RequestedPackageLineItem') on this ShipmentRequest object. See examples/create_shipment.py for more details. """ self.RequestedShipment.RequestedPackageLineItems.append(package_item) package_weight = package_item.Weight.Value self.RequestedShipment.TotalWeight.Value += package_weight self.RequestedShipment.PackageCount += 1
[ "def", "add_package", "(", "self", ",", "package_item", ")", ":", "self", ".", "RequestedShipment", ".", "RequestedPackageLineItems", ".", "append", "(", "package_item", ")", "package_weight", "=", "package_item", ".", "Weight", ".", "Value", "self", ".", "Reque...
Adds a package to the ship request. @type package_item: WSDL object, type of RequestedPackageLineItem WSDL object. @keyword package_item: A RequestedPackageLineItem, created by calling create_wsdl_object_of_type('RequestedPackageLineItem') on this ShipmentRequest object. See examples/create_shipment.py for more details.
[ "Adds", "a", "package", "to", "the", "ship", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L149-L164
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexDeleteShipmentRequest._prepare_wsdl_objects
def _prepare_wsdl_objects(self): """ Preps the WSDL data structures for the user. """ self.DeletionControlType = self.client.factory.create('DeletionControlType') self.TrackingId = self.client.factory.create('TrackingId') self.TrackingId.TrackingIdType = self.client.factory.create('TrackingIdType')
python
def _prepare_wsdl_objects(self): """ Preps the WSDL data structures for the user. """ self.DeletionControlType = self.client.factory.create('DeletionControlType') self.TrackingId = self.client.factory.create('TrackingId') self.TrackingId.TrackingIdType = self.client.factory.create('TrackingIdType')
[ "def", "_prepare_wsdl_objects", "(", "self", ")", ":", "self", ".", "DeletionControlType", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'DeletionControlType'", ")", "self", ".", "TrackingId", "=", "self", ".", "client", ".", "factory", "....
Preps the WSDL data structures for the user.
[ "Preps", "the", "WSDL", "data", "structures", "for", "the", "user", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L191-L198
python-fedex-devs/python-fedex
fedex/services/ship_service.py
FedexDeleteShipmentRequest._assemble_and_send_request
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ client = self.client # Fire off the query. return client.service.deleteShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, ShipTimestamp=datetime.datetime.now(), TrackingId=self.TrackingId, DeletionControl=self.DeletionControlType)
python
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ client = self.client # Fire off the query. return client.service.deleteShipment( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, ShipTimestamp=datetime.datetime.now(), TrackingId=self.TrackingId, DeletionControl=self.DeletionControlType)
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "client", "=", "self", ".", "client", "# Fire off the query.", "return", "client", ".", "service", ".", "deleteShipment", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "C...
Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/ship_service.py#L200-L217
python-fedex-devs/python-fedex
fedex/services/document_service.py
FedexDocumentServiceRequest._prepare_wsdl_objects
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ self.UploadDocumentsRequest = self.client.factory.create('UploadDocumentsRequest') self.OriginCountryCode =None self.DestinationCountryCode =None self.Usage ='ELECTRONIC_TRADE_DOCUMENTS'#Default Usage self.Documents = [] self.UploadDocumentsRequest.Documents = [] self.logger.debug(self.UploadDocumentsRequest)
python
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ self.UploadDocumentsRequest = self.client.factory.create('UploadDocumentsRequest') self.OriginCountryCode =None self.DestinationCountryCode =None self.Usage ='ELECTRONIC_TRADE_DOCUMENTS'#Default Usage self.Documents = [] self.UploadDocumentsRequest.Documents = [] self.logger.debug(self.UploadDocumentsRequest)
[ "def", "_prepare_wsdl_objects", "(", "self", ")", ":", "self", ".", "UploadDocumentsRequest", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'UploadDocumentsRequest'", ")", "self", ".", "OriginCountryCode", "=", "None", "self", ".", "Destinatio...
This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request.
[ "This", "is", "the", "data", "that", "will", "be", "used", "to", "create", "your", "shipment", ".", "Create", "the", "data", "structure", "and", "get", "it", "ready", "for", "the", "WSDL", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/document_service.py#L41-L52
python-fedex-devs/python-fedex
fedex/services/document_service.py
FedexDocumentServiceRequest._assemble_and_send_request
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.uploadDocuments( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, Documents=self.Documents, Usage = self.Usage, OriginCountryCode = self.OriginCountryCode, DestinationCountryCode = self.DestinationCountryCode, )
python
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.uploadDocuments( WebAuthenticationDetail=self.WebAuthenticationDetail, ClientDetail=self.ClientDetail, TransactionDetail=self.TransactionDetail, Version=self.VersionId, Documents=self.Documents, Usage = self.Usage, OriginCountryCode = self.OriginCountryCode, DestinationCountryCode = self.DestinationCountryCode, )
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "uploadDocuments", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=", "self",...
Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED.
[ "Fires", "off", "the", "Fedex", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/document_service.py#L54-L72
python-fedex-devs/python-fedex
fedex/base_service.py
FedexBaseService.__set_web_authentication_detail
def __set_web_authentication_detail(self): """ Sets up the WebAuthenticationDetail node. This is required for all requests. """ # Start of the authentication stuff. web_authentication_credential = self.client.factory.create('WebAuthenticationCredential') web_authentication_credential.Key = self.config_obj.key web_authentication_credential.Password = self.config_obj.password # Encapsulates the auth credentials. web_authentication_detail = self.client.factory.create('WebAuthenticationDetail') web_authentication_detail.UserCredential = web_authentication_credential # Set Default ParentCredential if hasattr(web_authentication_detail, 'ParentCredential'): web_authentication_detail.ParentCredential = web_authentication_credential self.WebAuthenticationDetail = web_authentication_detail
python
def __set_web_authentication_detail(self): """ Sets up the WebAuthenticationDetail node. This is required for all requests. """ # Start of the authentication stuff. web_authentication_credential = self.client.factory.create('WebAuthenticationCredential') web_authentication_credential.Key = self.config_obj.key web_authentication_credential.Password = self.config_obj.password # Encapsulates the auth credentials. web_authentication_detail = self.client.factory.create('WebAuthenticationDetail') web_authentication_detail.UserCredential = web_authentication_credential # Set Default ParentCredential if hasattr(web_authentication_detail, 'ParentCredential'): web_authentication_detail.ParentCredential = web_authentication_credential self.WebAuthenticationDetail = web_authentication_detail
[ "def", "__set_web_authentication_detail", "(", "self", ")", ":", "# Start of the authentication stuff.", "web_authentication_credential", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'WebAuthenticationCredential'", ")", "web_authentication_credential", "."...
Sets up the WebAuthenticationDetail node. This is required for all requests.
[ "Sets", "up", "the", "WebAuthenticationDetail", "node", ".", "This", "is", "required", "for", "all", "requests", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/base_service.py#L158-L177
python-fedex-devs/python-fedex
fedex/base_service.py
FedexBaseService.__set_client_detail
def __set_client_detail(self, *args, **kwargs): """ Sets up the ClientDetail node, which is required for all shipping related requests. """ client_detail = self.client.factory.create('ClientDetail') client_detail.AccountNumber = self.config_obj.account_number client_detail.MeterNumber = self.config_obj.meter_number client_detail.IntegratorId = self.config_obj.integrator_id if hasattr(client_detail, 'Region'): client_detail.Region = self.config_obj.express_region_code client_language_code = kwargs.get('client_language_code', None) client_locale_code = kwargs.get('client_locale_code', None) if hasattr(client_detail, 'Localization') and (client_language_code or client_locale_code): localization = self.client.factory.create('Localization') if client_language_code: localization.LanguageCode = client_language_code if client_locale_code: localization.LocaleCode = client_locale_code client_detail.Localization = localization self.ClientDetail = client_detail
python
def __set_client_detail(self, *args, **kwargs): """ Sets up the ClientDetail node, which is required for all shipping related requests. """ client_detail = self.client.factory.create('ClientDetail') client_detail.AccountNumber = self.config_obj.account_number client_detail.MeterNumber = self.config_obj.meter_number client_detail.IntegratorId = self.config_obj.integrator_id if hasattr(client_detail, 'Region'): client_detail.Region = self.config_obj.express_region_code client_language_code = kwargs.get('client_language_code', None) client_locale_code = kwargs.get('client_locale_code', None) if hasattr(client_detail, 'Localization') and (client_language_code or client_locale_code): localization = self.client.factory.create('Localization') if client_language_code: localization.LanguageCode = client_language_code if client_locale_code: localization.LocaleCode = client_locale_code client_detail.Localization = localization self.ClientDetail = client_detail
[ "def", "__set_client_detail", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "client_detail", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'ClientDetail'", ")", "client_detail", ".", "AccountNumber", "=", "self", ".",...
Sets up the ClientDetail node, which is required for all shipping related requests.
[ "Sets", "up", "the", "ClientDetail", "node", "which", "is", "required", "for", "all", "shipping", "related", "requests", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/base_service.py#L179-L206
python-fedex-devs/python-fedex
fedex/base_service.py
FedexBaseService.__set_transaction_detail
def __set_transaction_detail(self, *args, **kwargs): """ Checks kwargs for 'customer_transaction_id' and sets it if present. """ customer_transaction_id = kwargs.get('customer_transaction_id', None) if customer_transaction_id: transaction_detail = self.client.factory.create('TransactionDetail') transaction_detail.CustomerTransactionId = customer_transaction_id self.logger.debug(transaction_detail) self.TransactionDetail = transaction_detail
python
def __set_transaction_detail(self, *args, **kwargs): """ Checks kwargs for 'customer_transaction_id' and sets it if present. """ customer_transaction_id = kwargs.get('customer_transaction_id', None) if customer_transaction_id: transaction_detail = self.client.factory.create('TransactionDetail') transaction_detail.CustomerTransactionId = customer_transaction_id self.logger.debug(transaction_detail) self.TransactionDetail = transaction_detail
[ "def", "__set_transaction_detail", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "customer_transaction_id", "=", "kwargs", ".", "get", "(", "'customer_transaction_id'", ",", "None", ")", "if", "customer_transaction_id", ":", "transaction_detail...
Checks kwargs for 'customer_transaction_id' and sets it if present.
[ "Checks", "kwargs", "for", "customer_transaction_id", "and", "sets", "it", "if", "present", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/base_service.py#L208-L218
python-fedex-devs/python-fedex
fedex/base_service.py
FedexBaseService.__set_version_id
def __set_version_id(self): """ Pulles the versioning info for the request from the child request. """ version_id = self.client.factory.create('VersionId') version_id.ServiceId = self._version_info['service_id'] version_id.Major = self._version_info['major'] version_id.Intermediate = self._version_info['intermediate'] version_id.Minor = self._version_info['minor'] self.logger.debug(version_id) self.VersionId = version_id
python
def __set_version_id(self): """ Pulles the versioning info for the request from the child request. """ version_id = self.client.factory.create('VersionId') version_id.ServiceId = self._version_info['service_id'] version_id.Major = self._version_info['major'] version_id.Intermediate = self._version_info['intermediate'] version_id.Minor = self._version_info['minor'] self.logger.debug(version_id) self.VersionId = version_id
[ "def", "__set_version_id", "(", "self", ")", ":", "version_id", "=", "self", ".", "client", ".", "factory", ".", "create", "(", "'VersionId'", ")", "version_id", ".", "ServiceId", "=", "self", ".", "_version_info", "[", "'service_id'", "]", "version_id", "."...
Pulles the versioning info for the request from the child request.
[ "Pulles", "the", "versioning", "info", "for", "the", "request", "from", "the", "child", "request", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/base_service.py#L220-L231
python-fedex-devs/python-fedex
fedex/base_service.py
FedexBaseService.__check_response_for_fedex_error
def __check_response_for_fedex_error(self): """ This checks the response for general Fedex errors that aren't related to any one WSDL. """ if self.response.HighestSeverity == "FAILURE": for notification in self.response.Notifications: if notification.Severity == "FAILURE": raise FedexFailure(notification.Code, notification.Message)
python
def __check_response_for_fedex_error(self): """ This checks the response for general Fedex errors that aren't related to any one WSDL. """ if self.response.HighestSeverity == "FAILURE": for notification in self.response.Notifications: if notification.Severity == "FAILURE": raise FedexFailure(notification.Code, notification.Message)
[ "def", "__check_response_for_fedex_error", "(", "self", ")", ":", "if", "self", ".", "response", ".", "HighestSeverity", "==", "\"FAILURE\"", ":", "for", "notification", "in", "self", ".", "response", ".", "Notifications", ":", "if", "notification", ".", "Severi...
This checks the response for general Fedex errors that aren't related to any one WSDL.
[ "This", "checks", "the", "response", "for", "general", "Fedex", "errors", "that", "aren", "t", "related", "to", "any", "one", "WSDL", "." ]
train
https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/base_service.py#L242-L252