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_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
treat_values
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Removes the nan, negative, and inf values in two numpy arrays""" sim_copy = np.copy(simulated_array) obs_copy = np.copy(observed_array) # Checking to see if the vectors are the same length assert sim_copy.ndim == 1, "The simulated array is not one dimensional." assert obs_copy.ndim == 1, "The observed array is not one dimensional." if sim_copy.size != obs_copy.size: raise RuntimeError("The two ndarrays are not the same size.") # Treat missing data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain nan values all_treatment_array = np.ones(obs_copy.size, dtype=bool) if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)): if replace_nan is not None: # Finding the NaNs sim_nan = np.isnan(sim_copy) obs_nan = np.isnan(obs_copy) # Replacing the NaNs with the input sim_copy[sim_nan] = replace_nan obs_copy[obs_nan] = replace_nan warnings.warn("Elements(s) {} contained NaN values in the simulated array and " "elements(s) {} contained NaN values in the observed array and have been " "replaced (Elements are zero indexed).".format(np.where(sim_nan)[0], np.where(obs_nan)[0]), UserWarning) else: # Getting the indices of the nan values, combining them, and informing user. nan_indices_fcst = ~np.isnan(sim_copy) nan_indices_obs = ~np.isnan(obs_copy) all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices) warnings.warn("Row(s) {} contained NaN values and the row(s) have been " "removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]), UserWarning) if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)): if replace_nan is not None: # Finding the NaNs sim_inf = np.isinf(sim_copy) obs_inf = np.isinf(obs_copy) # Replacing the NaNs with the input sim_copy[sim_inf] = replace_inf obs_copy[obs_inf] = replace_inf warnings.warn("Elements(s) {} contained Inf values in the simulated array and " "elements(s) {} contained Inf values in the observed array and have been " "replaced (Elements are zero indexed).".format(np.where(sim_inf)[0], np.where(obs_inf)[0]), UserWarning) else: inf_indices_fcst = ~(np.isinf(sim_copy)) inf_indices_obs = ~np.isinf(obs_copy) all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices) warnings.warn( "Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows " "are zero indexed).".format(np.where(~all_inf_indices)[0]), UserWarning ) # Treat zero data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain zero values if remove_zero: if (obs_copy == 0).any() or (sim_copy == 0).any(): zero_indices_fcst = ~(sim_copy == 0) zero_indices_obs = ~(obs_copy == 0) all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices) warnings.warn( "Row(s) {} contained zero values and the row(s) have been removed (Rows are " "zero indexed).".format(np.where(~all_zero_indices)[0]), UserWarning ) # Treat negative data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain negative values # Ignore runtime warnings from comparing if remove_neg: with np.errstate(invalid='ignore'): obs_copy_bool = obs_copy < 0 sim_copy_bool = sim_copy < 0 if obs_copy_bool.any() or sim_copy_bool.any(): neg_indices_fcst = ~sim_copy_bool neg_indices_obs = ~obs_copy_bool all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices) warnings.warn("Row(s) {} contained negative values and the row(s) have been " "removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]), UserWarning) obs_copy = obs_copy[all_treatment_array] sim_copy = sim_copy[all_treatment_array] return sim_copy, obs_copy
python
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Removes the nan, negative, and inf values in two numpy arrays""" sim_copy = np.copy(simulated_array) obs_copy = np.copy(observed_array) # Checking to see if the vectors are the same length assert sim_copy.ndim == 1, "The simulated array is not one dimensional." assert obs_copy.ndim == 1, "The observed array is not one dimensional." if sim_copy.size != obs_copy.size: raise RuntimeError("The two ndarrays are not the same size.") # Treat missing data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain nan values all_treatment_array = np.ones(obs_copy.size, dtype=bool) if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)): if replace_nan is not None: # Finding the NaNs sim_nan = np.isnan(sim_copy) obs_nan = np.isnan(obs_copy) # Replacing the NaNs with the input sim_copy[sim_nan] = replace_nan obs_copy[obs_nan] = replace_nan warnings.warn("Elements(s) {} contained NaN values in the simulated array and " "elements(s) {} contained NaN values in the observed array and have been " "replaced (Elements are zero indexed).".format(np.where(sim_nan)[0], np.where(obs_nan)[0]), UserWarning) else: # Getting the indices of the nan values, combining them, and informing user. nan_indices_fcst = ~np.isnan(sim_copy) nan_indices_obs = ~np.isnan(obs_copy) all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices) warnings.warn("Row(s) {} contained NaN values and the row(s) have been " "removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]), UserWarning) if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)): if replace_nan is not None: # Finding the NaNs sim_inf = np.isinf(sim_copy) obs_inf = np.isinf(obs_copy) # Replacing the NaNs with the input sim_copy[sim_inf] = replace_inf obs_copy[obs_inf] = replace_inf warnings.warn("Elements(s) {} contained Inf values in the simulated array and " "elements(s) {} contained Inf values in the observed array and have been " "replaced (Elements are zero indexed).".format(np.where(sim_inf)[0], np.where(obs_inf)[0]), UserWarning) else: inf_indices_fcst = ~(np.isinf(sim_copy)) inf_indices_obs = ~np.isinf(obs_copy) all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices) warnings.warn( "Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows " "are zero indexed).".format(np.where(~all_inf_indices)[0]), UserWarning ) # Treat zero data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain zero values if remove_zero: if (obs_copy == 0).any() or (sim_copy == 0).any(): zero_indices_fcst = ~(sim_copy == 0) zero_indices_obs = ~(obs_copy == 0) all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices) warnings.warn( "Row(s) {} contained zero values and the row(s) have been removed (Rows are " "zero indexed).".format(np.where(~all_zero_indices)[0]), UserWarning ) # Treat negative data in observed_array and simulated_array, rows in simulated_array or # observed_array that contain negative values # Ignore runtime warnings from comparing if remove_neg: with np.errstate(invalid='ignore'): obs_copy_bool = obs_copy < 0 sim_copy_bool = sim_copy < 0 if obs_copy_bool.any() or sim_copy_bool.any(): neg_indices_fcst = ~sim_copy_bool neg_indices_obs = ~obs_copy_bool all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs) all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices) warnings.warn("Row(s) {} contained negative values and the row(s) have been " "removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]), UserWarning) obs_copy = obs_copy[all_treatment_array] sim_copy = sim_copy[all_treatment_array] return sim_copy, obs_copy
Removes the nan, negative, and inf values in two numpy arrays
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L6210-L6315
jgorset/fandjango
fandjango/decorators.py
facebook_authorization_required
def facebook_authorization_required(redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL, permissions=None): """ Require the user to authorize the application. :param redirect_uri: A string describing an URL to redirect to after authorization is complete. If ``None``, redirects to the current URL in the Facebook canvas (e.g. ``http://apps.facebook.com/myapp/current/path``). Defaults to ``FACEBOOK_AUTHORIZATION_REDIRECT_URL`` (which, in turn, defaults to ``None``). :param permissions: A list of strings describing Facebook permissions. """ def decorator(function): @wraps(function) def wrapper(request, *args, **kwargs): # We know the user has been authenticated via a canvas page if a signed request is set. canvas = request.facebook is not False and hasattr(request.facebook, "signed_request") # The user has already authorized the application, but the given view requires # permissions besides the defaults listed in ``FACEBOOK_APPLICATION_DEFAULT_PERMISSIONS``. # # Derive a list of outstanding permissions and prompt the user to grant them. if request.facebook and request.facebook.user and permissions: outstanding_permissions = [p for p in permissions if p not in request.facebook.user.permissions] if outstanding_permissions: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = outstanding_permissions ) # The user has not authorized the application yet. # # Concatenate the default permissions with permissions required for this particular view. if not request.facebook or not request.facebook.user: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = (FACEBOOK_APPLICATION_INITIAL_PERMISSIONS or []) + (permissions or []) ) return function(request, *args, **kwargs) return wrapper if callable(redirect_uri): function = redirect_uri redirect_uri = None return decorator(function) else: return decorator
python
def facebook_authorization_required(redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL, permissions=None): """ Require the user to authorize the application. :param redirect_uri: A string describing an URL to redirect to after authorization is complete. If ``None``, redirects to the current URL in the Facebook canvas (e.g. ``http://apps.facebook.com/myapp/current/path``). Defaults to ``FACEBOOK_AUTHORIZATION_REDIRECT_URL`` (which, in turn, defaults to ``None``). :param permissions: A list of strings describing Facebook permissions. """ def decorator(function): @wraps(function) def wrapper(request, *args, **kwargs): # We know the user has been authenticated via a canvas page if a signed request is set. canvas = request.facebook is not False and hasattr(request.facebook, "signed_request") # The user has already authorized the application, but the given view requires # permissions besides the defaults listed in ``FACEBOOK_APPLICATION_DEFAULT_PERMISSIONS``. # # Derive a list of outstanding permissions and prompt the user to grant them. if request.facebook and request.facebook.user and permissions: outstanding_permissions = [p for p in permissions if p not in request.facebook.user.permissions] if outstanding_permissions: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = outstanding_permissions ) # The user has not authorized the application yet. # # Concatenate the default permissions with permissions required for this particular view. if not request.facebook or not request.facebook.user: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = (FACEBOOK_APPLICATION_INITIAL_PERMISSIONS or []) + (permissions or []) ) return function(request, *args, **kwargs) return wrapper if callable(redirect_uri): function = redirect_uri redirect_uri = None return decorator(function) else: return decorator
Require the user to authorize the application. :param redirect_uri: A string describing an URL to redirect to after authorization is complete. If ``None``, redirects to the current URL in the Facebook canvas (e.g. ``http://apps.facebook.com/myapp/current/path``). Defaults to ``FACEBOOK_AUTHORIZATION_REDIRECT_URL`` (which, in turn, defaults to ``None``). :param permissions: A list of strings describing Facebook permissions.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/decorators.py#L14-L65
jgorset/fandjango
fandjango/models.py
User.full_name
def full_name(self): """Return the user's first name.""" if self.first_name and self.middle_name and self.last_name: return "%s %s %s" % (self.first_name, self.middle_name, self.last_name) if self.first_name and self.last_name: return "%s %s" % (self.first_name, self.last_name)
python
def full_name(self): """Return the user's first name.""" if self.first_name and self.middle_name and self.last_name: return "%s %s %s" % (self.first_name, self.middle_name, self.last_name) if self.first_name and self.last_name: return "%s %s" % (self.first_name, self.last_name)
Return the user's first name.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L86-L91
jgorset/fandjango
fandjango/models.py
User.permissions
def permissions(self): """ A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/ """ records = self.graph.get('me/permissions')['data'] permissions = [] for record in records: if record['status'] == 'granted': permissions.append(record['permission']) return permissions
python
def permissions(self): """ A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/ """ records = self.graph.get('me/permissions')['data'] permissions = [] for record in records: if record['status'] == 'granted': permissions.append(record['permission']) return permissions
A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L102-L115
jgorset/fandjango
fandjango/models.py
User.synchronize
def synchronize(self, graph_data=None): """ Synchronize ``facebook_username``, ``first_name``, ``middle_name``, ``last_name`` and ``birthday`` with Facebook. :param graph_data: Optional pre-fetched graph data """ profile = graph_data or self.graph.get('me') self.facebook_username = profile.get('username') self.first_name = profile.get('first_name') self.middle_name = profile.get('middle_name') self.last_name = profile.get('last_name') self.birthday = datetime.strptime(profile['birthday'], '%m/%d/%Y') if profile.has_key('birthday') else None self.email = profile.get('email') self.locale = profile.get('locale') self.gender = profile.get('gender') self.extra_data = profile self.save()
python
def synchronize(self, graph_data=None): """ Synchronize ``facebook_username``, ``first_name``, ``middle_name``, ``last_name`` and ``birthday`` with Facebook. :param graph_data: Optional pre-fetched graph data """ profile = graph_data or self.graph.get('me') self.facebook_username = profile.get('username') self.first_name = profile.get('first_name') self.middle_name = profile.get('middle_name') self.last_name = profile.get('last_name') self.birthday = datetime.strptime(profile['birthday'], '%m/%d/%Y') if profile.has_key('birthday') else None self.email = profile.get('email') self.locale = profile.get('locale') self.gender = profile.get('gender') self.extra_data = profile self.save()
Synchronize ``facebook_username``, ``first_name``, ``middle_name``, ``last_name`` and ``birthday`` with Facebook. :param graph_data: Optional pre-fetched graph data
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L126-L144
jgorset/fandjango
fandjango/models.py
OAuthToken.extended
def extended(self): """Determine whether the OAuth token has been extended.""" if self.expires_at: return self.expires_at - self.issued_at > timedelta(days=30) else: return False
python
def extended(self): """Determine whether the OAuth token has been extended.""" if self.expires_at: return self.expires_at - self.issued_at > timedelta(days=30) else: return False
Determine whether the OAuth token has been extended.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L179-L184
jgorset/fandjango
fandjango/models.py
OAuthToken.extend
def extend(self): """Extend the OAuth token.""" graph = GraphAPI() response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, client_secret = FACEBOOK_APPLICATION_SECRET_KEY, grant_type = 'fb_exchange_token', fb_exchange_token = self.token ) components = parse_qs(response) self.token = components['access_token'][0] self.expires_at = now() + timedelta(seconds = int(components['expires'][0])) self.save()
python
def extend(self): """Extend the OAuth token.""" graph = GraphAPI() response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, client_secret = FACEBOOK_APPLICATION_SECRET_KEY, grant_type = 'fb_exchange_token', fb_exchange_token = self.token ) components = parse_qs(response) self.token = components['access_token'][0] self.expires_at = now() + timedelta(seconds = int(components['expires'][0])) self.save()
Extend the OAuth token.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L186-L202
jgorset/fandjango
fandjango/middleware.py
FacebookMiddleware.process_request
def process_request(self, request): """Process the signed request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) # No signed request found in either GET, POST nor COOKIES... if 'signed_request' not in request.REQUEST and 'signed_request' not in request.COOKIES: return # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' request.facebook = Facebook() try: request.facebook.signed_request = SignedRequest( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) except SignedRequest.Error: request.facebook = False # Valid signed request and user has authorized the application if request.facebook \ and request.facebook.signed_request.user.has_authorized_application \ and not request.facebook.signed_request.user.oauth_token.has_expired: # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.user.oauth_token.token, issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()), expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = now() if 'signed_request' in request.REQUEST: user.authorized = True if request.facebook.signed_request.user.oauth_token: user.oauth_token.token = request.facebook.signed_request.user.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()) user.oauth_token.expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) user.oauth_token.save() user.save() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user
python
def process_request(self, request): """Process the signed request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) # No signed request found in either GET, POST nor COOKIES... if 'signed_request' not in request.REQUEST and 'signed_request' not in request.COOKIES: return # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' request.facebook = Facebook() try: request.facebook.signed_request = SignedRequest( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) except SignedRequest.Error: request.facebook = False # Valid signed request and user has authorized the application if request.facebook \ and request.facebook.signed_request.user.has_authorized_application \ and not request.facebook.signed_request.user.oauth_token.has_expired: # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.user.oauth_token.token, issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()), expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = now() if 'signed_request' in request.REQUEST: user.authorized = True if request.facebook.signed_request.user.oauth_token: user.oauth_token.token = request.facebook.signed_request.user.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()) user.oauth_token.expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) user.oauth_token.save() user.save() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user
Process the signed request.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L53-L141
jgorset/fandjango
fandjango/middleware.py
FacebookMiddleware.process_response
def process_response(self, request, response): """ Set compact P3P policies and save signed request to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' if FANDJANGO_CACHE_SIGNED_REQUEST: if hasattr(request, "facebook") and request.facebook and request.facebook.signed_request: response.set_cookie('signed_request', request.facebook.signed_request.generate()) else: response.delete_cookie('signed_request') return response
python
def process_response(self, request, response): """ Set compact P3P policies and save signed request to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' if FANDJANGO_CACHE_SIGNED_REQUEST: if hasattr(request, "facebook") and request.facebook and request.facebook.signed_request: response.set_cookie('signed_request', request.facebook.signed_request.generate()) else: response.delete_cookie('signed_request') return response
Set compact P3P policies and save signed request to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L143-L159
jgorset/fandjango
fandjango/middleware.py
FacebookWebMiddleware.process_request
def process_request(self, request): """Process the web-based auth request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) request.facebook = Facebook() oauth_token = False # Is there a token cookie already present? if 'oauth_token' in request.COOKIES: try: # Check if the current token is already in DB oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token']) except OAuthToken.DoesNotExist: request.facebook = False return # Is there a code in the GET request? elif 'code' in request.GET: try: graph = GraphAPI() # Exchange code for an access_token response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, redirect_uri = get_post_authorization_redirect_url(request, canvas=False), client_secret = FACEBOOK_APPLICATION_SECRET_KEY, code = request.GET['code'], ) components = parse_qs(response) # Save new OAuth-token in DB oauth_token, new_oauth_token = OAuthToken.objects.get_or_create( token = components['access_token'][0], issued_at = now(), expires_at = now() + timedelta(seconds = int(components['expires'][0])) ) except GraphAPI.OAuthError: pass # There isn't a valid access_token if not oauth_token or oauth_token.expired: request.facebook = False return # Is there a user already connected to the current token? try: user = oauth_token.user if not user.authorized: request.facebook = False return user.last_seen_at = now() user.save() except User.DoesNotExist: graph = GraphAPI(oauth_token.token) profile = graph.get('me') # Either the user already exists and its just a new token, or user and token both are new try: user = User.objects.get(facebook_id = profile.get('id')) if not user.authorized: if new_oauth_token: user.last_seen_at = now() user.authorized = True else: request.facebook = False return except User.DoesNotExist: # Create a new user to go with token user = User.objects.create( facebook_id = profile.get('id'), oauth_token = oauth_token ) user.synchronize(profile) # Delete old access token if there is any and only if the new one is different old_oauth_token = None if user.oauth_token != oauth_token: old_oauth_token = user.oauth_token user.oauth_token = oauth_token user.save() if old_oauth_token: old_oauth_token.delete() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user request.facebook.oauth_token = oauth_token
python
def process_request(self, request): """Process the web-based auth request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) request.facebook = Facebook() oauth_token = False # Is there a token cookie already present? if 'oauth_token' in request.COOKIES: try: # Check if the current token is already in DB oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token']) except OAuthToken.DoesNotExist: request.facebook = False return # Is there a code in the GET request? elif 'code' in request.GET: try: graph = GraphAPI() # Exchange code for an access_token response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, redirect_uri = get_post_authorization_redirect_url(request, canvas=False), client_secret = FACEBOOK_APPLICATION_SECRET_KEY, code = request.GET['code'], ) components = parse_qs(response) # Save new OAuth-token in DB oauth_token, new_oauth_token = OAuthToken.objects.get_or_create( token = components['access_token'][0], issued_at = now(), expires_at = now() + timedelta(seconds = int(components['expires'][0])) ) except GraphAPI.OAuthError: pass # There isn't a valid access_token if not oauth_token or oauth_token.expired: request.facebook = False return # Is there a user already connected to the current token? try: user = oauth_token.user if not user.authorized: request.facebook = False return user.last_seen_at = now() user.save() except User.DoesNotExist: graph = GraphAPI(oauth_token.token) profile = graph.get('me') # Either the user already exists and its just a new token, or user and token both are new try: user = User.objects.get(facebook_id = profile.get('id')) if not user.authorized: if new_oauth_token: user.last_seen_at = now() user.authorized = True else: request.facebook = False return except User.DoesNotExist: # Create a new user to go with token user = User.objects.create( facebook_id = profile.get('id'), oauth_token = oauth_token ) user.synchronize(profile) # Delete old access token if there is any and only if the new one is different old_oauth_token = None if user.oauth_token != oauth_token: old_oauth_token = user.oauth_token user.oauth_token = oauth_token user.save() if old_oauth_token: old_oauth_token.delete() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user request.facebook.oauth_token = oauth_token
Process the web-based auth request.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L164-L274
jgorset/fandjango
fandjango/middleware.py
FacebookWebMiddleware.process_response
def process_response(self, request, response): """ Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ if hasattr(request, "facebook") and request.facebook and request.facebook.oauth_token: if "code" in request.REQUEST: """ Remove auth related query params """ path = get_full_path(request, remove_querystrings=['code', 'web_canvas']) response = HttpResponseRedirect(path) response.set_cookie('oauth_token', request.facebook.oauth_token.token) else: response.delete_cookie('oauth_token') response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' return response
python
def process_response(self, request, response): """ Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ if hasattr(request, "facebook") and request.facebook and request.facebook.oauth_token: if "code" in request.REQUEST: """ Remove auth related query params """ path = get_full_path(request, remove_querystrings=['code', 'web_canvas']) response = HttpResponseRedirect(path) response.set_cookie('oauth_token', request.facebook.oauth_token.token) else: response.delete_cookie('oauth_token') response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' return response
Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L277-L297
thombashi/SimpleSQLite
simplesqlite/_logger/_logger.py
set_log_level
def set_log_level(log_level): """ Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value. """ if not LOGBOOK_INSTALLED: return # validate log level logbook.get_level_name(log_level) if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level tabledata.set_log_level(log_level) sqliteschema.set_log_level(log_level) try: import pytablereader pytablereader.set_log_level(log_level) except ImportError: pass
python
def set_log_level(log_level): """ Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value. """ if not LOGBOOK_INSTALLED: return # validate log level logbook.get_level_name(log_level) if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level tabledata.set_log_level(log_level) sqliteschema.set_log_level(log_level) try: import pytablereader pytablereader.set_log_level(log_level) except ImportError: pass
Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_logger/_logger.py#L49-L83
thombashi/SimpleSQLite
simplesqlite/converter.py
RecordConvertor.to_record
def to_record(cls, attr_names, values): """ Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid. """ try: # from a namedtuple to a dict values = values._asdict() except AttributeError: pass try: # from a dictionary to a list return [cls.__to_sqlite_element(values.get(attr_name)) for attr_name in attr_names] except AttributeError: pass if isinstance(values, (tuple, list)): return [cls.__to_sqlite_element(value) for value in values] raise ValueError("cannot convert from {} to list".format(type(values)))
python
def to_record(cls, attr_names, values): """ Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid. """ try: # from a namedtuple to a dict values = values._asdict() except AttributeError: pass try: # from a dictionary to a list return [cls.__to_sqlite_element(values.get(attr_name)) for attr_name in attr_names] except AttributeError: pass if isinstance(values, (tuple, list)): return [cls.__to_sqlite_element(value) for value in values] raise ValueError("cannot convert from {} to list".format(type(values)))
Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/converter.py#L21-L47
thombashi/SimpleSQLite
simplesqlite/converter.py
RecordConvertor.to_records
def to_records(cls, attr_names, value_matrix): """ Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_record` """ return [cls.to_record(attr_names, record) for record in value_matrix]
python
def to_records(cls, attr_names, value_matrix): """ Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_record` """ return [cls.to_record(attr_names, record) for record in value_matrix]
Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_record`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/converter.py#L50-L62
jgorset/fandjango
fandjango/utils.py
is_disabled_path
def is_disabled_path(path): """ Determine whether or not the path matches one or more paths in the DISABLED_PATHS setting. :param path: A string describing the path to be matched. """ for disabled_path in DISABLED_PATHS: match = re.search(disabled_path, path[1:]) if match: return True return False
python
def is_disabled_path(path): """ Determine whether or not the path matches one or more paths in the DISABLED_PATHS setting. :param path: A string describing the path to be matched. """ for disabled_path in DISABLED_PATHS: match = re.search(disabled_path, path[1:]) if match: return True return False
Determine whether or not the path matches one or more paths in the DISABLED_PATHS setting. :param path: A string describing the path to be matched.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L17-L28
jgorset/fandjango
fandjango/utils.py
is_enabled_path
def is_enabled_path(path): """ Determine whether or not the path matches one or more paths in the ENABLED_PATHS setting. :param path: A string describing the path to be matched. """ for enabled_path in ENABLED_PATHS: match = re.search(enabled_path, path[1:]) if match: return True return False
python
def is_enabled_path(path): """ Determine whether or not the path matches one or more paths in the ENABLED_PATHS setting. :param path: A string describing the path to be matched. """ for enabled_path in ENABLED_PATHS: match = re.search(enabled_path, path[1:]) if match: return True return False
Determine whether or not the path matches one or more paths in the ENABLED_PATHS setting. :param path: A string describing the path to be matched.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L30-L41
jgorset/fandjango
fandjango/utils.py
cached_property
def cached_property(**kwargs): """Cache the return value of a property.""" def decorator(function): @wraps(function) def wrapper(self): key = 'fandjango.%(model)s.%(property)s_%(pk)s' % { 'model': self.__class__.__name__, 'pk': self.pk, 'property': function.__name__ } cached_value = cache.get(key) delta = timedelta(**kwargs) if cached_value is None: value = function(self) cache.set(key, value, delta.days * 86400 + delta.seconds) else: value = cached_value return value return wrapper return decorator
python
def cached_property(**kwargs): """Cache the return value of a property.""" def decorator(function): @wraps(function) def wrapper(self): key = 'fandjango.%(model)s.%(property)s_%(pk)s' % { 'model': self.__class__.__name__, 'pk': self.pk, 'property': function.__name__ } cached_value = cache.get(key) delta = timedelta(**kwargs) if cached_value is None: value = function(self) cache.set(key, value, delta.days * 86400 + delta.seconds) else: value = cached_value return value return wrapper return decorator
Cache the return value of a property.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L43-L66
jgorset/fandjango
fandjango/utils.py
authorization_denied_view
def authorization_denied_view(request): """Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``.""" authorization_denied_module_name = AUTHORIZATION_DENIED_VIEW.rsplit('.', 1)[0] authorization_denied_view_name = AUTHORIZATION_DENIED_VIEW.split('.')[-1] authorization_denied_module = import_module(authorization_denied_module_name) authorization_denied_view = getattr(authorization_denied_module, authorization_denied_view_name) return authorization_denied_view(request)
python
def authorization_denied_view(request): """Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``.""" authorization_denied_module_name = AUTHORIZATION_DENIED_VIEW.rsplit('.', 1)[0] authorization_denied_view_name = AUTHORIZATION_DENIED_VIEW.split('.')[-1] authorization_denied_module = import_module(authorization_denied_module_name) authorization_denied_view = getattr(authorization_denied_module, authorization_denied_view_name) return authorization_denied_view(request)
Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L68-L76
jgorset/fandjango
fandjango/utils.py
get_post_authorization_redirect_url
def get_post_authorization_redirect_url(request, canvas=True): """ Determine the URL users should be redirected to upon authorization the application. If request is non-canvas use user defined site url if set, else the site hostname. """ path = request.get_full_path() if canvas: if FACEBOOK_APPLICATION_CANVAS_URL: path = path.replace(urlparse(FACEBOOK_APPLICATION_CANVAS_URL).path, '') redirect_uri = 'https://%(domain)s/%(namespace)s%(path)s' % { 'domain': FACEBOOK_APPLICATION_DOMAIN, 'namespace': FACEBOOK_APPLICATION_NAMESPACE, 'path': path } else: if FANDJANGO_SITE_URL: site_url = FANDJANGO_SITE_URL path = path.replace(urlparse(site_url).path, '') else: protocol = "https" if request.is_secure() else "http" site_url = "%s://%s" % (protocol, request.get_host()) redirect_uri = site_url + path return redirect_uri
python
def get_post_authorization_redirect_url(request, canvas=True): """ Determine the URL users should be redirected to upon authorization the application. If request is non-canvas use user defined site url if set, else the site hostname. """ path = request.get_full_path() if canvas: if FACEBOOK_APPLICATION_CANVAS_URL: path = path.replace(urlparse(FACEBOOK_APPLICATION_CANVAS_URL).path, '') redirect_uri = 'https://%(domain)s/%(namespace)s%(path)s' % { 'domain': FACEBOOK_APPLICATION_DOMAIN, 'namespace': FACEBOOK_APPLICATION_NAMESPACE, 'path': path } else: if FANDJANGO_SITE_URL: site_url = FANDJANGO_SITE_URL path = path.replace(urlparse(site_url).path, '') else: protocol = "https" if request.is_secure() else "http" site_url = "%s://%s" % (protocol, request.get_host()) redirect_uri = site_url + path return redirect_uri
Determine the URL users should be redirected to upon authorization the application. If request is non-canvas use user defined site url if set, else the site hostname.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L78-L105
jgorset/fandjango
fandjango/utils.py
get_full_path
def get_full_path(request, remove_querystrings=[]): """Gets the current path, removing specified querstrings""" path = request.get_full_path() for qs in remove_querystrings: path = re.sub(r'&?' + qs + '=?(.+)?&?', '', path) return path
python
def get_full_path(request, remove_querystrings=[]): """Gets the current path, removing specified querstrings""" path = request.get_full_path() for qs in remove_querystrings: path = re.sub(r'&?' + qs + '=?(.+)?&?', '', path) return path
Gets the current path, removing specified querstrings
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L107-L113
jgorset/fandjango
fandjango/views.py
authorize_application
def authorize_application( request, redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE), permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS ): """ Redirect the user to authorize the application. Redirection is done by rendering a JavaScript snippet that redirects the parent window to the authorization URI, since Facebook will not allow this inside an iframe. """ query = { 'client_id': FACEBOOK_APPLICATION_ID, 'redirect_uri': redirect_uri } if permissions: query['scope'] = ', '.join(permissions) return render( request = request, template_name = 'fandjango/authorize_application.html', dictionary = { 'url': 'https://www.facebook.com/dialog/oauth?%s' % urlencode(query) }, status = 401 )
python
def authorize_application( request, redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE), permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS ): """ Redirect the user to authorize the application. Redirection is done by rendering a JavaScript snippet that redirects the parent window to the authorization URI, since Facebook will not allow this inside an iframe. """ query = { 'client_id': FACEBOOK_APPLICATION_ID, 'redirect_uri': redirect_uri } if permissions: query['scope'] = ', '.join(permissions) return render( request = request, template_name = 'fandjango/authorize_application.html', dictionary = { 'url': 'https://www.facebook.com/dialog/oauth?%s' % urlencode(query) }, status = 401 )
Redirect the user to authorize the application. Redirection is done by rendering a JavaScript snippet that redirects the parent window to the authorization URI, since Facebook will not allow this inside an iframe.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/views.py#L15-L41
jgorset/fandjango
fandjango/views.py
deauthorize_application
def deauthorize_application(request): """ When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding users as unauthorized. """ if request.facebook: user = User.objects.get( facebook_id = request.facebook.signed_request.user.id ) user.authorized = False user.save() return HttpResponse() else: return HttpResponse(status=400)
python
def deauthorize_application(request): """ When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding users as unauthorized. """ if request.facebook: user = User.objects.get( facebook_id = request.facebook.signed_request.user.id ) user.authorized = False user.save() return HttpResponse() else: return HttpResponse(status=400)
When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding users as unauthorized.
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/views.py#L53-L69
thombashi/SimpleSQLite
simplesqlite/sqlquery.py
SqlQuery.make_insert
def make_insert(cls, table, insert_tuple): """ [Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple`` is empty |list|/|tuple|. :raises simplesqlite.NameValidationError: |raises_validate_table_name| """ validate_table_name(table) table = Table(table) if typepy.is_empty_sequence(insert_tuple): raise ValueError("empty insert list/tuple") return "INSERT INTO {:s} VALUES ({:s})".format( table, ",".join(["?" for _i in insert_tuple]) )
python
def make_insert(cls, table, insert_tuple): """ [Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple`` is empty |list|/|tuple|. :raises simplesqlite.NameValidationError: |raises_validate_table_name| """ validate_table_name(table) table = Table(table) if typepy.is_empty_sequence(insert_tuple): raise ValueError("empty insert list/tuple") return "INSERT INTO {:s} VALUES ({:s})".format( table, ",".join(["?" for _i in insert_tuple]) )
[Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple`` is empty |list|/|tuple|. :raises simplesqlite.NameValidationError: |raises_validate_table_name|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/sqlquery.py#L22-L44
thombashi/SimpleSQLite
simplesqlite/sqlquery.py
SqlQuery.make_update
def make_update(cls, table, set_query, where=None): """ Make UPDATE query. :param str table: Table name of executing the query. :param str set_query: SET part of the UPDATE query. :param str where: Add a WHERE clause to execute query, if the value is not |None|. :return: Query of SQLite. :rtype: str :raises ValueError: If ``set_query`` is empty string. :raises simplesqlite.NameValidationError: |raises_validate_table_name| """ validate_table_name(table) if typepy.is_null_string(set_query): raise ValueError("SET query is null") query_list = ["UPDATE {:s}".format(Table(table)), "SET {:s}".format(set_query)] if where and isinstance(where, (six.text_type, Where, And, Or)): query_list.append("WHERE {:s}".format(where)) return " ".join(query_list)
python
def make_update(cls, table, set_query, where=None): """ Make UPDATE query. :param str table: Table name of executing the query. :param str set_query: SET part of the UPDATE query. :param str where: Add a WHERE clause to execute query, if the value is not |None|. :return: Query of SQLite. :rtype: str :raises ValueError: If ``set_query`` is empty string. :raises simplesqlite.NameValidationError: |raises_validate_table_name| """ validate_table_name(table) if typepy.is_null_string(set_query): raise ValueError("SET query is null") query_list = ["UPDATE {:s}".format(Table(table)), "SET {:s}".format(set_query)] if where and isinstance(where, (six.text_type, Where, And, Or)): query_list.append("WHERE {:s}".format(where)) return " ".join(query_list)
Make UPDATE query. :param str table: Table name of executing the query. :param str set_query: SET part of the UPDATE query. :param str where: Add a WHERE clause to execute query, if the value is not |None|. :return: Query of SQLite. :rtype: str :raises ValueError: If ``set_query`` is empty string. :raises simplesqlite.NameValidationError: |raises_validate_table_name|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/sqlquery.py#L47-L71
thombashi/SimpleSQLite
simplesqlite/sqlquery.py
SqlQuery.make_where_in
def make_where_in(cls, key, value_list): """ Make part of WHERE IN query. :param str key: Attribute name of the key. :param str value_list: List of values that the right hand side associated with the key. :return: Part of WHERE query of SQLite. :rtype: str :Examples: >>> from simplesqlite.sqlquery import SqlQuery >>> SqlQuery.make_where_in("key", ["hoge", "foo", "bar"]) "key IN ('hoge', 'foo', 'bar')" """ return "{:s} IN ({:s})".format( Attr(key), ", ".join([Value(value).to_query() for value in value_list]) )
python
def make_where_in(cls, key, value_list): """ Make part of WHERE IN query. :param str key: Attribute name of the key. :param str value_list: List of values that the right hand side associated with the key. :return: Part of WHERE query of SQLite. :rtype: str :Examples: >>> from simplesqlite.sqlquery import SqlQuery >>> SqlQuery.make_where_in("key", ["hoge", "foo", "bar"]) "key IN ('hoge', 'foo', 'bar')" """ return "{:s} IN ({:s})".format( Attr(key), ", ".join([Value(value).to_query() for value in value_list]) )
Make part of WHERE IN query. :param str key: Attribute name of the key. :param str value_list: List of values that the right hand side associated with the key. :return: Part of WHERE query of SQLite. :rtype: str :Examples: >>> from simplesqlite.sqlquery import SqlQuery >>> SqlQuery.make_where_in("key", ["hoge", "foo", "bar"]) "key IN ('hoge', 'foo', 'bar')"
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/sqlquery.py#L74-L92
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.connect
def connect(self, database_path, mode="a"): """ Connect to a SQLite database. :param str database_path: Path to the SQLite database file to be connected. :param str mode: ``"r"``: Open for read only. ``"w"``: Open for read/write. Delete existing tables when connecting. ``"a"``: Open for read/write. Append to the existing tables. :raises ValueError: If ``database_path`` is invalid or |attr_mode| is invalid. :raises simplesqlite.DatabaseError: If the file is encrypted or is not a database. :raises simplesqlite.OperationalError: If unable to open the database file. """ self.close() logger.debug("connect to a SQLite database: path='{}', mode={}".format(database_path, mode)) if mode == "r": self.__verify_db_file_existence(database_path) elif mode in ["w", "a"]: self.__validate_db_path(database_path) else: raise ValueError("unknown connection mode: " + mode) if database_path == MEMORY_DB_NAME: self.__database_path = database_path else: self.__database_path = os.path.realpath(database_path) try: self.__connection = sqlite3.connect(database_path) except sqlite3.OperationalError as e: raise OperationalError(e) self.__mode = mode try: # validate connection after connect self.fetch_table_names() except sqlite3.DatabaseError as e: raise DatabaseError(e) if mode != "w": return for table in self.fetch_table_names(): self.drop_table(table)
python
def connect(self, database_path, mode="a"): """ Connect to a SQLite database. :param str database_path: Path to the SQLite database file to be connected. :param str mode: ``"r"``: Open for read only. ``"w"``: Open for read/write. Delete existing tables when connecting. ``"a"``: Open for read/write. Append to the existing tables. :raises ValueError: If ``database_path`` is invalid or |attr_mode| is invalid. :raises simplesqlite.DatabaseError: If the file is encrypted or is not a database. :raises simplesqlite.OperationalError: If unable to open the database file. """ self.close() logger.debug("connect to a SQLite database: path='{}', mode={}".format(database_path, mode)) if mode == "r": self.__verify_db_file_existence(database_path) elif mode in ["w", "a"]: self.__validate_db_path(database_path) else: raise ValueError("unknown connection mode: " + mode) if database_path == MEMORY_DB_NAME: self.__database_path = database_path else: self.__database_path = os.path.realpath(database_path) try: self.__connection = sqlite3.connect(database_path) except sqlite3.OperationalError as e: raise OperationalError(e) self.__mode = mode try: # validate connection after connect self.fetch_table_names() except sqlite3.DatabaseError as e: raise DatabaseError(e) if mode != "w": return for table in self.fetch_table_names(): self.drop_table(table)
Connect to a SQLite database. :param str database_path: Path to the SQLite database file to be connected. :param str mode: ``"r"``: Open for read only. ``"w"``: Open for read/write. Delete existing tables when connecting. ``"a"``: Open for read/write. Append to the existing tables. :raises ValueError: If ``database_path`` is invalid or |attr_mode| is invalid. :raises simplesqlite.DatabaseError: If the file is encrypted or is not a database. :raises simplesqlite.OperationalError: If unable to open the database file.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L216-L268
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.execute_query
def execute_query(self, query, caller=None): """ Send arbitrary SQLite query to the database. :param str query: Query to executed. :param tuple caller: Caller information. Expects the return value of :py:meth:`logging.Logger.findCaller`. :return: The result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| .. warning:: This method can execute an arbitrary query. i.e. No access permissions check by |attr_mode|. """ import time self.check_connection() if typepy.is_null_string(query): return None if self.debug_query or self.global_debug_query: logger.debug(query) if self.__is_profile: exec_start_time = time.time() try: result = self.connection.execute(six.text_type(query)) except (sqlite3.OperationalError, sqlite3.IntegrityError) as e: if caller is None: caller = logging.getLogger().findCaller() file_path, line_no, func_name = caller[:3] raise OperationalError( message="\n".join( [ "failed to execute query at {:s}({:d}) {:s}".format( file_path, line_no, func_name ), " - query: {}".format(MultiByteStrDecoder(query).unicode_str), " - msg: {}".format(e), " - db: {}".format(self.database_path), ] ) ) if self.__is_profile: self.__dict_query_count[query] = self.__dict_query_count.get(query, 0) + 1 elapse_time = time.time() - exec_start_time self.__dict_query_totalexectime[query] = ( self.__dict_query_totalexectime.get(query, 0) + elapse_time ) return result
python
def execute_query(self, query, caller=None): """ Send arbitrary SQLite query to the database. :param str query: Query to executed. :param tuple caller: Caller information. Expects the return value of :py:meth:`logging.Logger.findCaller`. :return: The result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| .. warning:: This method can execute an arbitrary query. i.e. No access permissions check by |attr_mode|. """ import time self.check_connection() if typepy.is_null_string(query): return None if self.debug_query or self.global_debug_query: logger.debug(query) if self.__is_profile: exec_start_time = time.time() try: result = self.connection.execute(six.text_type(query)) except (sqlite3.OperationalError, sqlite3.IntegrityError) as e: if caller is None: caller = logging.getLogger().findCaller() file_path, line_no, func_name = caller[:3] raise OperationalError( message="\n".join( [ "failed to execute query at {:s}({:d}) {:s}".format( file_path, line_no, func_name ), " - query: {}".format(MultiByteStrDecoder(query).unicode_str), " - msg: {}".format(e), " - db: {}".format(self.database_path), ] ) ) if self.__is_profile: self.__dict_query_count[query] = self.__dict_query_count.get(query, 0) + 1 elapse_time = time.time() - exec_start_time self.__dict_query_totalexectime[query] = ( self.__dict_query_totalexectime.get(query, 0) + elapse_time ) return result
Send arbitrary SQLite query to the database. :param str query: Query to executed. :param tuple caller: Caller information. Expects the return value of :py:meth:`logging.Logger.findCaller`. :return: The result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| .. warning:: This method can execute an arbitrary query. i.e. No access permissions check by |attr_mode|.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L270-L329
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.select
def select(self, select, table_name, where=None, extra=None): """ Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ self.verify_table_existence(table_name) return self.execute_query( six.text_type(Select(select, table_name, where, extra)), logging.getLogger().findCaller(), )
python
def select(self, select, table_name, where=None, extra=None): """ Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ self.verify_table_existence(table_name) return self.execute_query( six.text_type(Select(select, table_name, where, extra)), logging.getLogger().findCaller(), )
Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Result of the query execution. :rtype: sqlite3.Cursor :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L340-L363
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.select_as_dataframe
def select_as_dataframe(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a :py:class:`pandas.Dataframe` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param str where: |arg_select_where| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`pandas.Dataframe` instance. :rtype: pandas.DataFrame :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dataframe` .. note:: ``pandas`` package required to execute this method. """ import pandas if columns is None: columns = self.fetch_attr_names(table_name) result = self.select( select=AttrList(columns), table_name=table_name, where=where, extra=extra ) if result is None: return pandas.DataFrame() return pandas.DataFrame(result.fetchall(), columns=columns)
python
def select_as_dataframe(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a :py:class:`pandas.Dataframe` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param str where: |arg_select_where| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`pandas.Dataframe` instance. :rtype: pandas.DataFrame :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dataframe` .. note:: ``pandas`` package required to execute this method. """ import pandas if columns is None: columns = self.fetch_attr_names(table_name) result = self.select( select=AttrList(columns), table_name=table_name, where=where, extra=extra ) if result is None: return pandas.DataFrame() return pandas.DataFrame(result.fetchall(), columns=columns)
Get data in the database and return fetched data as a :py:class:`pandas.Dataframe` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param str where: |arg_select_where| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`pandas.Dataframe` instance. :rtype: pandas.DataFrame :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dataframe` .. note:: ``pandas`` package required to execute this method.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L365-L401
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.select_as_tabledata
def select_as_tabledata( self, table_name, columns=None, where=None, extra=None, type_hints=None ): """ Get data in the database and return fetched data as a :py:class:`tabledata.TableData` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`tabledata.TableData` instance. :rtype: tabledata.TableData :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| .. note:: ``pandas`` package required to execute this method. """ if columns is None: columns = self.fetch_attr_names(table_name) result = self.select( select=AttrList(columns), table_name=table_name, where=where, extra=extra ) if result is None: return TableData(None, [], []) if type_hints is None: type_hints = self.fetch_data_types(table_name) return TableData( table_name, columns, result.fetchall(), type_hints=[type_hints.get(col) for col in columns], )
python
def select_as_tabledata( self, table_name, columns=None, where=None, extra=None, type_hints=None ): """ Get data in the database and return fetched data as a :py:class:`tabledata.TableData` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`tabledata.TableData` instance. :rtype: tabledata.TableData :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| .. note:: ``pandas`` package required to execute this method. """ if columns is None: columns = self.fetch_attr_names(table_name) result = self.select( select=AttrList(columns), table_name=table_name, where=where, extra=extra ) if result is None: return TableData(None, [], []) if type_hints is None: type_hints = self.fetch_data_types(table_name) return TableData( table_name, columns, result.fetchall(), type_hints=[type_hints.get(col) for col in columns], )
Get data in the database and return fetched data as a :py:class:`tabledata.TableData` instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a :py:class:`tabledata.TableData` instance. :rtype: tabledata.TableData :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| .. note:: ``pandas`` package required to execute this method.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L403-L445
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.select_as_dict
def select_as_dict(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a |OrderedDict| list. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as |OrderedDict| instances. :rtype: |list| of |OrderedDict| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dict` """ return self.select_as_tabledata(table_name, columns, where, extra).as_dict().get(table_name)
python
def select_as_dict(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a |OrderedDict| list. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as |OrderedDict| instances. :rtype: |list| of |OrderedDict| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dict` """ return self.select_as_tabledata(table_name, columns, where, extra).as_dict().get(table_name)
Get data in the database and return fetched data as a |OrderedDict| list. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as |OrderedDict| instances. :rtype: |list| of |OrderedDict| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-select-as-dict`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L447-L469
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.select_as_memdb
def select_as_memdb(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a in-memory |SimpleSQLite| instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a |SimpleSQLite| instance that connected to in memory database. :rtype: |SimpleSQLite| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ table_schema = self.schema_extractor.fetch_table_schema(table_name) memdb = connect_memdb() memdb.create_table_from_tabledata( self.select_as_tabledata(table_name, columns, where, extra), primary_key=table_schema.primary_key, index_attrs=table_schema.index_list, ) return memdb
python
def select_as_memdb(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a in-memory |SimpleSQLite| instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a |SimpleSQLite| instance that connected to in memory database. :rtype: |SimpleSQLite| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ table_schema = self.schema_extractor.fetch_table_schema(table_name) memdb = connect_memdb() memdb.create_table_from_tabledata( self.select_as_tabledata(table_name, columns, where, extra), primary_key=table_schema.primary_key, index_attrs=table_schema.index_list, ) return memdb
Get data in the database and return fetched data as a in-memory |SimpleSQLite| instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Table data as a |SimpleSQLite| instance that connected to in memory database. :rtype: |SimpleSQLite| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L471-L501
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.insert
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records` """ self.insert_many(table_name, records=[record], attr_names=attr_names)
python
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records` """ self.insert_many(table_name, records=[record], attr_names=attr_names)
Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L503-L519
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.insert_many
def insert_many(self, table_name, records, attr_names=None): """ Send an INSERT query with multiple records to the database. :param str table: Table name of executing the query. :param records: Records to be inserted. :type records: list of |dict|/|namedtuple|/|list|/|tuple| :return: Number of inserted records. :rtype: int :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records` """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) if attr_names: logger.debug( "insert {number} records into {table}({attrs})".format( number=len(records) if records else 0, table=table_name, attrs=attr_names ) ) else: logger.debug( "insert {number} records into {table}".format( number=len(records) if records else 0, table=table_name ) ) if typepy.is_empty_sequence(records): return 0 if attr_names is None: attr_names = self.fetch_attr_names(table_name) records = RecordConvertor.to_records(attr_names, records) query = Insert(table_name, AttrList(attr_names)).to_query() if self.debug_query or self.global_debug_query: logging_count = 8 num_records = len(records) logs = [query] + [ " record {:4d}: {}".format(i, record) for i, record in enumerate(records[:logging_count]) ] if num_records - logging_count > 0: logs.append( " and other {} records will be inserted".format(num_records - logging_count) ) logger.debug("\n".join(logs)) try: self.connection.executemany(query, records) except (sqlite3.OperationalError, sqlite3.IntegrityError) as e: caller = logging.getLogger().findCaller() file_path, line_no, func_name = caller[:3] raise OperationalError( "{:s}({:d}) {:s}: failed to execute query:\n".format(file_path, line_no, func_name) + " query={}\n".format(query) + " msg='{}'\n".format(e) + " db={}\n".format(self.database_path) + " records={}\n".format(records[:2]) ) return len(records)
python
def insert_many(self, table_name, records, attr_names=None): """ Send an INSERT query with multiple records to the database. :param str table: Table name of executing the query. :param records: Records to be inserted. :type records: list of |dict|/|namedtuple|/|list|/|tuple| :return: Number of inserted records. :rtype: int :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records` """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) if attr_names: logger.debug( "insert {number} records into {table}({attrs})".format( number=len(records) if records else 0, table=table_name, attrs=attr_names ) ) else: logger.debug( "insert {number} records into {table}".format( number=len(records) if records else 0, table=table_name ) ) if typepy.is_empty_sequence(records): return 0 if attr_names is None: attr_names = self.fetch_attr_names(table_name) records = RecordConvertor.to_records(attr_names, records) query = Insert(table_name, AttrList(attr_names)).to_query() if self.debug_query or self.global_debug_query: logging_count = 8 num_records = len(records) logs = [query] + [ " record {:4d}: {}".format(i, record) for i, record in enumerate(records[:logging_count]) ] if num_records - logging_count > 0: logs.append( " and other {} records will be inserted".format(num_records - logging_count) ) logger.debug("\n".join(logs)) try: self.connection.executemany(query, records) except (sqlite3.OperationalError, sqlite3.IntegrityError) as e: caller = logging.getLogger().findCaller() file_path, line_no, func_name = caller[:3] raise OperationalError( "{:s}({:d}) {:s}: failed to execute query:\n".format(file_path, line_no, func_name) + " query={}\n".format(query) + " msg='{}'\n".format(e) + " db={}\n".format(self.database_path) + " records={}\n".format(records[:2]) ) return len(records)
Send an INSERT query with multiple records to the database. :param str table: Table name of executing the query. :param records: Records to be inserted. :type records: list of |dict|/|namedtuple|/|list|/|tuple| :return: Number of inserted records. :rtype: int :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-insert-records`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L521-L593
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.update
def update(self, table_name, set_query, where=None): """Execute an UPDATE query. Args: table_name (|str|): Table name of executing the query. set_query (|str|): ``SET`` clause for the update query. where (|arg_where_type| , optional): ``WHERE`` clause for the update query. Defaults to |None|. Raises: IOError: |raises_write_permission| simplesqlite.NullDatabaseConnectionError: |raises_check_connection| simplesqlite.TableNotFoundError: |raises_verify_table_existence| simplesqlite.OperationalError: |raises_operational_error| """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) query = SqlQuery.make_update(table_name, set_query, where) return self.execute_query(query, logging.getLogger().findCaller())
python
def update(self, table_name, set_query, where=None): """Execute an UPDATE query. Args: table_name (|str|): Table name of executing the query. set_query (|str|): ``SET`` clause for the update query. where (|arg_where_type| , optional): ``WHERE`` clause for the update query. Defaults to |None|. Raises: IOError: |raises_write_permission| simplesqlite.NullDatabaseConnectionError: |raises_check_connection| simplesqlite.TableNotFoundError: |raises_verify_table_existence| simplesqlite.OperationalError: |raises_operational_error| """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) query = SqlQuery.make_update(table_name, set_query, where) return self.execute_query(query, logging.getLogger().findCaller())
Execute an UPDATE query. Args: table_name (|str|): Table name of executing the query. set_query (|str|): ``SET`` clause for the update query. where (|arg_where_type| , optional): ``WHERE`` clause for the update query. Defaults to |None|. Raises: IOError: |raises_write_permission| simplesqlite.NullDatabaseConnectionError: |raises_check_connection| simplesqlite.TableNotFoundError: |raises_verify_table_existence| simplesqlite.OperationalError: |raises_operational_error|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L595-L623
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.delete
def delete(self, table_name, where=None): """ Send a DELETE query to the database. :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) query = "DELETE FROM {:s}".format(table_name) if where: query += " WHERE {:s}".format(where) return self.execute_query(query, logging.getLogger().findCaller())
python
def delete(self, table_name, where=None): """ Send a DELETE query to the database. :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| """ self.validate_access_permission(["w", "a"]) self.verify_table_existence(table_name) query = "DELETE FROM {:s}".format(table_name) if where: query += " WHERE {:s}".format(where) return self.execute_query(query, logging.getLogger().findCaller())
Send a DELETE query to the database. :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L625-L641
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.fetch_value
def fetch_value(self, select, table_name, where=None, extra=None): """ Fetch a value from the table. Return |None| if no value matches the conditions, or the table not found in the database. :param str select: Attribute for SELECT query :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| :return: Result of execution of the query. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| """ try: self.verify_table_existence(table_name) except TableNotFoundError as e: logger.debug(e) return None result = self.execute_query( Select(select, table_name, where, extra), logging.getLogger().findCaller() ) if result is None: return None fetch = result.fetchone() if fetch is None: return None return fetch[0]
python
def fetch_value(self, select, table_name, where=None, extra=None): """ Fetch a value from the table. Return |None| if no value matches the conditions, or the table not found in the database. :param str select: Attribute for SELECT query :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| :return: Result of execution of the query. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| """ try: self.verify_table_existence(table_name) except TableNotFoundError as e: logger.debug(e) return None result = self.execute_query( Select(select, table_name, where, extra), logging.getLogger().findCaller() ) if result is None: return None fetch = result.fetchone() if fetch is None: return None return fetch[0]
Fetch a value from the table. Return |None| if no value matches the conditions, or the table not found in the database. :param str select: Attribute for SELECT query :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| :return: Result of execution of the query. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L643-L674
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.fetch_table_names
def fetch_table_names(self, include_system_table=False): """ :return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_table_names()) :Output: .. code-block:: python ['hoge'] """ self.check_connection() return self.schema_extractor.fetch_table_names(include_system_table)
python
def fetch_table_names(self, include_system_table=False): """ :return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_table_names()) :Output: .. code-block:: python ['hoge'] """ self.check_connection() return self.schema_extractor.fetch_table_names(include_system_table)
:return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_table_names()) :Output: .. code-block:: python ['hoge']
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L683-L710
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.fetch_attr_names
def fetch_attr_names(self, table_name): """ :return: List of attribute names in the table. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_attr_names(table_name)) try: print(con.fetch_attr_names("not_existing")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: ['attr_a', 'attr_b'] 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) return self.schema_extractor.fetch_table_schema(table_name).get_attr_names()
python
def fetch_attr_names(self, table_name): """ :return: List of attribute names in the table. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_attr_names(table_name)) try: print(con.fetch_attr_names("not_existing")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: ['attr_a', 'attr_b'] 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) return self.schema_extractor.fetch_table_schema(table_name).get_attr_names()
:return: List of attribute names in the table. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.fetch_attr_names(table_name)) try: print(con.fetch_attr_names("not_existing")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: ['attr_a', 'attr_b'] 'not_existing' table not found in /tmp/sample.sqlite
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L719-L756
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.fetch_attr_type
def fetch_attr_type(self, table_name): """ :return: Dictionary of attribute names and attribute types in the table. :rtype: dict :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ self.verify_table_existence(table_name) result = self.execute_query( "SELECT sql FROM sqlite_master WHERE type='table' and name={:s}".format( Value(table_name) ) ) query = result.fetchone()[0] match = re.search("[(].*[)]", query) def get_entry(items): key = " ".join(items[:-1]) value = items[-1] return [key, value] return dict([get_entry(item.split(" ")) for item in match.group().strip("()").split(", ")])
python
def fetch_attr_type(self, table_name): """ :return: Dictionary of attribute names and attribute types in the table. :rtype: dict :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error| """ self.verify_table_existence(table_name) result = self.execute_query( "SELECT sql FROM sqlite_master WHERE type='table' and name={:s}".format( Value(table_name) ) ) query = result.fetchone()[0] match = re.search("[(].*[)]", query) def get_entry(items): key = " ".join(items[:-1]) value = items[-1] return [key, value] return dict([get_entry(item.split(" ")) for item in match.group().strip("()").split(", ")])
:return: Dictionary of attribute names and attribute types in the table. :rtype: dict :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.OperationalError: |raises_operational_error|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L765-L793
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.fetch_num_records
def fetch_num_records(self, table_name, where=None): """ Fetch the number of records in a table. :param str table_name: Table name to get number of records. :param where: |arg_select_where| :type where: |arg_where_type| :return: Number of records in the table. |None| if no value matches the conditions, or the table not found in the database. :rtype: int """ return self.fetch_value(select="COUNT(*)", table_name=table_name, where=where)
python
def fetch_num_records(self, table_name, where=None): """ Fetch the number of records in a table. :param str table_name: Table name to get number of records. :param where: |arg_select_where| :type where: |arg_where_type| :return: Number of records in the table. |None| if no value matches the conditions, or the table not found in the database. :rtype: int """ return self.fetch_value(select="COUNT(*)", table_name=table_name, where=where)
Fetch the number of records in a table. :param str table_name: Table name to get number of records. :param where: |arg_select_where| :type where: |arg_where_type| :return: Number of records in the table. |None| if no value matches the conditions, or the table not found in the database. :rtype: int
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L795-L809
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.get_profile
def get_profile(self, profile_count=50): """ Get profile of query execution time. :param int profile_count: Number of profiles to retrieve, counted from the top query in descending order by the cumulative execution time. :return: Profile information for each query. :rtype: list of |namedtuple| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-get-profile` """ from collections import namedtuple profile_table_name = "sql_profile" value_matrix = [ [query, execute_time, self.__dict_query_count.get(query, 0)] for query, execute_time in six.iteritems(self.__dict_query_totalexectime) ] attr_names = ("sql_query", "cumulative_time", "count") con_tmp = connect_memdb() try: con_tmp.create_table_from_data_matrix( profile_table_name, attr_names, data_matrix=value_matrix ) except ValueError: return [] try: result = con_tmp.select( select="{:s},SUM({:s}),SUM({:s})".format(*attr_names), table_name=profile_table_name, extra="GROUP BY {:s} ORDER BY {:s} DESC LIMIT {:d}".format( attr_names[0], attr_names[1], profile_count ), ) except sqlite3.OperationalError: return [] if result is None: return [] SqliteProfile = namedtuple("SqliteProfile", " ".join(attr_names)) return [SqliteProfile(*profile) for profile in result.fetchall()]
python
def get_profile(self, profile_count=50): """ Get profile of query execution time. :param int profile_count: Number of profiles to retrieve, counted from the top query in descending order by the cumulative execution time. :return: Profile information for each query. :rtype: list of |namedtuple| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-get-profile` """ from collections import namedtuple profile_table_name = "sql_profile" value_matrix = [ [query, execute_time, self.__dict_query_count.get(query, 0)] for query, execute_time in six.iteritems(self.__dict_query_totalexectime) ] attr_names = ("sql_query", "cumulative_time", "count") con_tmp = connect_memdb() try: con_tmp.create_table_from_data_matrix( profile_table_name, attr_names, data_matrix=value_matrix ) except ValueError: return [] try: result = con_tmp.select( select="{:s},SUM({:s}),SUM({:s})".format(*attr_names), table_name=profile_table_name, extra="GROUP BY {:s} ORDER BY {:s} DESC LIMIT {:d}".format( attr_names[0], attr_names[1], profile_count ), ) except sqlite3.OperationalError: return [] if result is None: return [] SqliteProfile = namedtuple("SqliteProfile", " ".join(attr_names)) return [SqliteProfile(*profile) for profile in result.fetchall()]
Get profile of query execution time. :param int profile_count: Number of profiles to retrieve, counted from the top query in descending order by the cumulative execution time. :return: Profile information for each query. :rtype: list of |namedtuple| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Example: :ref:`example-get-profile`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L816-L866
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.has_table
def has_table(self, table_name): """ :param str table_name: Table name to be tested. :return: |True| if the database has the table. :rtype: bool :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_table("hoge")) print(con.has_table("not_existing")) :Output: .. code-block:: python True False """ try: validate_table_name(table_name) except NameValidationError: return False return table_name in self.fetch_table_names()
python
def has_table(self, table_name): """ :param str table_name: Table name to be tested. :return: |True| if the database has the table. :rtype: bool :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_table("hoge")) print(con.has_table("not_existing")) :Output: .. code-block:: python True False """ try: validate_table_name(table_name) except NameValidationError: return False return table_name in self.fetch_table_names()
:param str table_name: Table name to be tested. :return: |True| if the database has the table. :rtype: bool :Sample Code: .. code:: python from simplesqlite import SimpleSQLite con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( "hoge", ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_table("hoge")) print(con.has_table("not_existing")) :Output: .. code-block:: python True False
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L922-L953
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.has_attr
def has_attr(self, table_name, attr_name): """ :param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to be tested. :return: |True| if the table has the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attr(table_name, "attr_a")) print(con.has_attr(table_name, "not_existing")) try: print(con.has_attr("not_existing", "attr_a")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True False 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) if typepy.is_null_string(attr_name): return False return attr_name in self.fetch_attr_names(table_name)
python
def has_attr(self, table_name, attr_name): """ :param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to be tested. :return: |True| if the table has the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attr(table_name, "attr_a")) print(con.has_attr(table_name, "not_existing")) try: print(con.has_attr("not_existing", "attr_a")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True False 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) if typepy.is_null_string(attr_name): return False return attr_name in self.fetch_attr_names(table_name)
:param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to be tested. :return: |True| if the table has the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attr(table_name, "attr_a")) print(con.has_attr(table_name, "not_existing")) try: print(con.has_attr("not_existing", "attr_a")) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True False 'not_existing' table not found in /tmp/sample.sqlite
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L955-L995
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.has_attrs
def has_attrs(self, table_name, attr_names): """ :param str table_name: Table name that attributes exists. :param str attr_names: Attribute names to tested. :return: |True| if the table has all of the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attrs(table_name, ["attr_a"])) print(con.has_attrs(table_name, ["attr_a", "attr_b"])) print(con.has_attrs(table_name, ["attr_a", "attr_b", "not_existing"])) try: print(con.has_attr("not_existing", ["attr_a"])) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True True False 'not_existing' table not found in /tmp/sample.sqlite """ if typepy.is_empty_sequence(attr_names): return False not_exist_fields = [ attr_name for attr_name in attr_names if not self.has_attr(table_name, attr_name) ] if not_exist_fields: return False return True
python
def has_attrs(self, table_name, attr_names): """ :param str table_name: Table name that attributes exists. :param str attr_names: Attribute names to tested. :return: |True| if the table has all of the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attrs(table_name, ["attr_a"])) print(con.has_attrs(table_name, ["attr_a", "attr_b"])) print(con.has_attrs(table_name, ["attr_a", "attr_b", "not_existing"])) try: print(con.has_attr("not_existing", ["attr_a"])) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True True False 'not_existing' table not found in /tmp/sample.sqlite """ if typepy.is_empty_sequence(attr_names): return False not_exist_fields = [ attr_name for attr_name in attr_names if not self.has_attr(table_name, attr_name) ] if not_exist_fields: return False return True
:param str table_name: Table name that attributes exists. :param str attr_names: Attribute names to tested. :return: |True| if the table has all of the attribute. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) print(con.has_attrs(table_name, ["attr_a"])) print(con.has_attrs(table_name, ["attr_a", "attr_b"])) print(con.has_attrs(table_name, ["attr_a", "attr_b", "not_existing"])) try: print(con.has_attr("not_existing", ["attr_a"])) except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: True True False 'not_existing' table not found in /tmp/sample.sqlite
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L997-L1044
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.verify_table_existence
def verify_table_existence(self, table_name): """ :param str table_name: Table name to be tested. :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_table_existence(table_name) try: con.verify_table_existence("not_existing") except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' table not found in /tmp/sample.sqlite """ validate_table_name(table_name) if self.has_table(table_name): return raise TableNotFoundError( "'{}' table not found in '{}' database".format(table_name, self.database_path) )
python
def verify_table_existence(self, table_name): """ :param str table_name: Table name to be tested. :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_table_existence(table_name) try: con.verify_table_existence("not_existing") except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' table not found in /tmp/sample.sqlite """ validate_table_name(table_name) if self.has_table(table_name): return raise TableNotFoundError( "'{}' table not found in '{}' database".format(table_name, self.database_path) )
:param str table_name: Table name to be tested. :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :Sample Code: .. code:: python import simplesqlite table_name = "sample_table" con = simplesqlite.SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_table_existence(table_name) try: con.verify_table_existence("not_existing") except simplesqlite.TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' table not found in /tmp/sample.sqlite
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1051-L1089
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.verify_attr_existence
def verify_attr_existence(self, table_name, attr_name): """ :param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to tested. :raises simplesqlite.AttributeNotFoundError: If attribute not found in the table :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python from simplesqlite import ( SimpleSQLite, TableNotFoundError, AttributeNotFoundError ) table_name = "sample_table" con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_attr_existence(table_name, "attr_a") try: con.verify_attr_existence(table_name, "not_existing") except AttributeNotFoundError as e: print(e) try: con.verify_attr_existence("not_existing", "attr_a") except TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' attribute not found in 'sample_table' table 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) if self.has_attr(table_name, attr_name): return raise AttributeNotFoundError( "'{}' attribute not found in '{}' table".format(attr_name, table_name) )
python
def verify_attr_existence(self, table_name, attr_name): """ :param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to tested. :raises simplesqlite.AttributeNotFoundError: If attribute not found in the table :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python from simplesqlite import ( SimpleSQLite, TableNotFoundError, AttributeNotFoundError ) table_name = "sample_table" con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_attr_existence(table_name, "attr_a") try: con.verify_attr_existence(table_name, "not_existing") except AttributeNotFoundError as e: print(e) try: con.verify_attr_existence("not_existing", "attr_a") except TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' attribute not found in 'sample_table' table 'not_existing' table not found in /tmp/sample.sqlite """ self.verify_table_existence(table_name) if self.has_attr(table_name, attr_name): return raise AttributeNotFoundError( "'{}' attribute not found in '{}' table".format(attr_name, table_name) )
:param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to tested. :raises simplesqlite.AttributeNotFoundError: If attribute not found in the table :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :Sample Code: .. code:: python from simplesqlite import ( SimpleSQLite, TableNotFoundError, AttributeNotFoundError ) table_name = "sample_table" con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b"], [[1, "a"], [2, "b"]]) con.verify_attr_existence(table_name, "attr_a") try: con.verify_attr_existence(table_name, "not_existing") except AttributeNotFoundError as e: print(e) try: con.verify_attr_existence("not_existing", "attr_a") except TableNotFoundError as e: print(e) :Output: .. parsed-literal:: 'not_existing' attribute not found in 'sample_table' table 'not_existing' table not found in /tmp/sample.sqlite
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1091-L1139
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.validate_access_permission
def validate_access_permission(self, valid_permissions): """ :param valid_permissions: List of permissions that access is allowed. :type valid_permissions: |list|/|tuple| :raises ValueError: If the |attr_mode| is invalid. :raises IOError: If the |attr_mode| not in the ``valid_permissions``. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| """ self.check_connection() if typepy.is_null_string(self.mode): raise ValueError("mode is not set") if self.mode not in valid_permissions: raise IOError( "invalid access: expected-mode='{}', current-mode='{}'".format( "' or '".join(valid_permissions), self.mode ) )
python
def validate_access_permission(self, valid_permissions): """ :param valid_permissions: List of permissions that access is allowed. :type valid_permissions: |list|/|tuple| :raises ValueError: If the |attr_mode| is invalid. :raises IOError: If the |attr_mode| not in the ``valid_permissions``. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| """ self.check_connection() if typepy.is_null_string(self.mode): raise ValueError("mode is not set") if self.mode not in valid_permissions: raise IOError( "invalid access: expected-mode='{}', current-mode='{}'".format( "' or '".join(valid_permissions), self.mode ) )
:param valid_permissions: List of permissions that access is allowed. :type valid_permissions: |list|/|tuple| :raises ValueError: If the |attr_mode| is invalid. :raises IOError: If the |attr_mode| not in the ``valid_permissions``. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1141-L1163
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.drop_table
def drop_table(self, table_name): """ :param str table_name: Table name to drop. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission| """ self.validate_access_permission(["w", "a"]) if table_name in SQLITE_SYSTEM_TABLES: # warning message return if self.has_table(table_name): query = "DROP TABLE IF EXISTS '{:s}'".format(table_name) self.execute_query(query, logging.getLogger().findCaller()) self.commit()
python
def drop_table(self, table_name): """ :param str table_name: Table name to drop. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission| """ self.validate_access_permission(["w", "a"]) if table_name in SQLITE_SYSTEM_TABLES: # warning message return if self.has_table(table_name): query = "DROP TABLE IF EXISTS '{:s}'".format(table_name) self.execute_query(query, logging.getLogger().findCaller()) self.commit()
:param str table_name: Table name to drop. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1165-L1182
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table
def create_table(self, table_name, attr_descriptions): """ :param str table_name: Table name to create. :param list attr_descriptions: List of table description. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission| """ self.validate_access_permission(["w", "a"]) table_name = table_name.strip() if self.has_table(table_name): return True query = "CREATE TABLE IF NOT EXISTS '{:s}' ({:s})".format( table_name, ", ".join(attr_descriptions) ) logger.debug(query) if self.execute_query(query, logging.getLogger().findCaller()) is None: return False return True
python
def create_table(self, table_name, attr_descriptions): """ :param str table_name: Table name to create. :param list attr_descriptions: List of table description. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission| """ self.validate_access_permission(["w", "a"]) table_name = table_name.strip() if self.has_table(table_name): return True query = "CREATE TABLE IF NOT EXISTS '{:s}' ({:s})".format( table_name, ", ".join(attr_descriptions) ) logger.debug(query) if self.execute_query(query, logging.getLogger().findCaller()) is None: return False return True
:param str table_name: Table name to create. :param list attr_descriptions: List of table description. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write_permission|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1184-L1207
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_index
def create_index(self, table_name, attr_name): """ :param str table_name: Table name that contains the attribute to be indexed. :param str attr_name: Attribute name to create index. :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| """ self.verify_table_existence(table_name) self.validate_access_permission(["w", "a"]) query_format = "CREATE INDEX IF NOT EXISTS {index:s} ON {table}({attr})" query = query_format.format( index=make_index_name(table_name, attr_name), table=Table(table_name), attr=Attr(attr_name), ) logger.debug(query) self.execute_query(query, logging.getLogger().findCaller())
python
def create_index(self, table_name, attr_name): """ :param str table_name: Table name that contains the attribute to be indexed. :param str attr_name: Attribute name to create index. :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| """ self.verify_table_existence(table_name) self.validate_access_permission(["w", "a"]) query_format = "CREATE INDEX IF NOT EXISTS {index:s} ON {table}({attr})" query = query_format.format( index=make_index_name(table_name, attr_name), table=Table(table_name), attr=Attr(attr_name), ) logger.debug(query) self.execute_query(query, logging.getLogger().findCaller())
:param str table_name: Table name that contains the attribute to be indexed. :param str attr_name: Attribute name to create index. :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1209-L1232
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_index_list
def create_index_list(self, table_name, attr_names): """ :param str table_name: Table name that exists attribute. :param list attr_names: List of attribute names to create indices. Ignore attributes that are not existing in the table. .. seealso:: :py:meth:`.create_index` """ self.validate_access_permission(["w", "a"]) if typepy.is_empty_sequence(attr_names): return table_attr_set = set(self.fetch_attr_names(table_name)) index_attr_set = set(AttrList.sanitize(attr_names)) for attribute in list(table_attr_set.intersection(index_attr_set)): self.create_index(table_name, attribute)
python
def create_index_list(self, table_name, attr_names): """ :param str table_name: Table name that exists attribute. :param list attr_names: List of attribute names to create indices. Ignore attributes that are not existing in the table. .. seealso:: :py:meth:`.create_index` """ self.validate_access_permission(["w", "a"]) if typepy.is_empty_sequence(attr_names): return table_attr_set = set(self.fetch_attr_names(table_name)) index_attr_set = set(AttrList.sanitize(attr_names)) for attribute in list(table_attr_set.intersection(index_attr_set)): self.create_index(table_name, attribute)
:param str table_name: Table name that exists attribute. :param list attr_names: List of attribute names to create indices. Ignore attributes that are not existing in the table. .. seealso:: :py:meth:`.create_index`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1234-L1253
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table_from_data_matrix
def create_table_from_data_matrix( self, table_name, attr_names, data_matrix, primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table if not exists. Moreover, insert data into the created table. :param str table_name: Table name to create. :param list attr_names: Attribute names of the table. :param data_matrix: Data to be inserted into the table. :type data_matrix: List of |dict|/|namedtuple|/|list|/|tuple| :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :raises simplesqlite.NameValidationError: |raises_validate_attr_name| :raises ValueError: If the ``data_matrix`` is empty. :Example: :ref:`example-create-table-from-data-matrix` .. seealso:: :py:meth:`.create_table` :py:meth:`.insert_many` :py:meth:`.create_index_list` """ self.__create_table_from_tabledata( TableData(table_name, attr_names, data_matrix), primary_key, add_primary_key_column, index_attrs, )
python
def create_table_from_data_matrix( self, table_name, attr_names, data_matrix, primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table if not exists. Moreover, insert data into the created table. :param str table_name: Table name to create. :param list attr_names: Attribute names of the table. :param data_matrix: Data to be inserted into the table. :type data_matrix: List of |dict|/|namedtuple|/|list|/|tuple| :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :raises simplesqlite.NameValidationError: |raises_validate_attr_name| :raises ValueError: If the ``data_matrix`` is empty. :Example: :ref:`example-create-table-from-data-matrix` .. seealso:: :py:meth:`.create_table` :py:meth:`.insert_many` :py:meth:`.create_index_list` """ self.__create_table_from_tabledata( TableData(table_name, attr_names, data_matrix), primary_key, add_primary_key_column, index_attrs, )
Create a table if not exists. Moreover, insert data into the created table. :param str table_name: Table name to create. :param list attr_names: Attribute names of the table. :param data_matrix: Data to be inserted into the table. :type data_matrix: List of |dict|/|namedtuple|/|list|/|tuple| :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises simplesqlite.NameValidationError: |raises_validate_table_name| :raises simplesqlite.NameValidationError: |raises_validate_attr_name| :raises ValueError: If the ``data_matrix`` is empty. :Example: :ref:`example-create-table-from-data-matrix` .. seealso:: :py:meth:`.create_table` :py:meth:`.insert_many` :py:meth:`.create_index_list`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1255-L1294
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table_from_tabledata
def create_table_from_tabledata( self, table_data, primary_key=None, add_primary_key_column=False, index_attrs=None ): """ Create a table from :py:class:`tabledata.TableData`. :param tabledata.TableData table_data: Table data to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| .. seealso:: :py:meth:`.create_table_from_data_matrix` """ self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
python
def create_table_from_tabledata( self, table_data, primary_key=None, add_primary_key_column=False, index_attrs=None ): """ Create a table from :py:class:`tabledata.TableData`. :param tabledata.TableData table_data: Table data to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| .. seealso:: :py:meth:`.create_table_from_data_matrix` """ self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
Create a table from :py:class:`tabledata.TableData`. :param tabledata.TableData table_data: Table data to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| .. seealso:: :py:meth:`.create_table_from_data_matrix`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1296-L1312
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table_from_csv
def create_table_from_csv( self, csv_source, table_name="", attr_names=(), delimiter=",", quotechar='"', encoding="utf-8", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a CSV file/text. :param str csv_source: Path to the CSV file or CSV text. :param str table_name: Table name to create. Using CSV file basename as the table name if the value is empty. :param list attr_names: Attribute names of the table. Use the first line of the CSV file as attributes if ``attr_names`` is empty. :param str delimiter: A one-character string used to separate fields. :param str quotechar: A one-character string used to quote fields containing special characters, such as the ``delimiter`` or ``quotechar``, or which contain new-line characters. :param str encoding: CSV file encoding. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises ValueError: If the CSV data is invalid. :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Example: :ref:`example-create-table-from-csv` .. seealso:: :py:meth:`.create_table_from_data_matrix` :py:func:`csv.reader` :py:meth:`.pytablereader.CsvTableFileLoader.load` :py:meth:`.pytablereader.CsvTableTextLoader.load` """ import pytablereader as ptr loader = ptr.CsvTableFileLoader(csv_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name loader.headers = attr_names loader.delimiter = delimiter loader.quotechar = quotechar loader.encoding = encoding try: for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs ) return except (ptr.InvalidFilePathError, IOError): pass loader = ptr.CsvTableTextLoader(csv_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name loader.headers = attr_names loader.delimiter = delimiter loader.quotechar = quotechar loader.encoding = encoding for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
python
def create_table_from_csv( self, csv_source, table_name="", attr_names=(), delimiter=",", quotechar='"', encoding="utf-8", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a CSV file/text. :param str csv_source: Path to the CSV file or CSV text. :param str table_name: Table name to create. Using CSV file basename as the table name if the value is empty. :param list attr_names: Attribute names of the table. Use the first line of the CSV file as attributes if ``attr_names`` is empty. :param str delimiter: A one-character string used to separate fields. :param str quotechar: A one-character string used to quote fields containing special characters, such as the ``delimiter`` or ``quotechar``, or which contain new-line characters. :param str encoding: CSV file encoding. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises ValueError: If the CSV data is invalid. :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Example: :ref:`example-create-table-from-csv` .. seealso:: :py:meth:`.create_table_from_data_matrix` :py:func:`csv.reader` :py:meth:`.pytablereader.CsvTableFileLoader.load` :py:meth:`.pytablereader.CsvTableTextLoader.load` """ import pytablereader as ptr loader = ptr.CsvTableFileLoader(csv_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name loader.headers = attr_names loader.delimiter = delimiter loader.quotechar = quotechar loader.encoding = encoding try: for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs ) return except (ptr.InvalidFilePathError, IOError): pass loader = ptr.CsvTableTextLoader(csv_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name loader.headers = attr_names loader.delimiter = delimiter loader.quotechar = quotechar loader.encoding = encoding for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
Create a table from a CSV file/text. :param str csv_source: Path to the CSV file or CSV text. :param str table_name: Table name to create. Using CSV file basename as the table name if the value is empty. :param list attr_names: Attribute names of the table. Use the first line of the CSV file as attributes if ``attr_names`` is empty. :param str delimiter: A one-character string used to separate fields. :param str quotechar: A one-character string used to quote fields containing special characters, such as the ``delimiter`` or ``quotechar``, or which contain new-line characters. :param str encoding: CSV file encoding. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :raises ValueError: If the CSV data is invalid. :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Example: :ref:`example-create-table-from-csv` .. seealso:: :py:meth:`.create_table_from_data_matrix` :py:func:`csv.reader` :py:meth:`.pytablereader.CsvTableFileLoader.load` :py:meth:`.pytablereader.CsvTableTextLoader.load`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1314-L1388
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table_from_json
def create_table_from_json( self, json_source, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a JSON file/text. :param str json_source: Path to the JSON file or JSON text. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Examples: :ref:`example-create-table-from-json` .. seealso:: :py:meth:`.pytablereader.JsonTableFileLoader.load` :py:meth:`.pytablereader.JsonTableTextLoader.load` """ import pytablereader as ptr loader = ptr.JsonTableFileLoader(json_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name try: for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs ) return except (ptr.InvalidFilePathError, IOError): pass loader = ptr.JsonTableTextLoader(json_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
python
def create_table_from_json( self, json_source, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a JSON file/text. :param str json_source: Path to the JSON file or JSON text. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Examples: :ref:`example-create-table-from-json` .. seealso:: :py:meth:`.pytablereader.JsonTableFileLoader.load` :py:meth:`.pytablereader.JsonTableTextLoader.load` """ import pytablereader as ptr loader = ptr.JsonTableFileLoader(json_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name try: for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs ) return except (ptr.InvalidFilePathError, IOError): pass loader = ptr.JsonTableTextLoader(json_source) if typepy.is_not_null_string(table_name): loader.table_name = table_name for table_data in loader.load(): self.__create_table_from_tabledata( table_data, primary_key, add_primary_key_column, index_attrs )
Create a table from a JSON file/text. :param str json_source: Path to the JSON file or JSON text. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Dependency Packages: - `pytablereader <https://github.com/thombashi/pytablereader>`__ :Examples: :ref:`example-create-table-from-json` .. seealso:: :py:meth:`.pytablereader.JsonTableFileLoader.load` :py:meth:`.pytablereader.JsonTableTextLoader.load`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1390-L1437
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.create_table_from_dataframe
def create_table_from_dataframe( self, dataframe, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: DataFrame instance to convert. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Examples: :ref:`example-create-table-from-df` """ self.__create_table_from_tabledata( TableData.from_dataframe(dataframe=dataframe, table_name=table_name), primary_key, add_primary_key_column, index_attrs, )
python
def create_table_from_dataframe( self, dataframe, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: DataFrame instance to convert. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Examples: :ref:`example-create-table-from-df` """ self.__create_table_from_tabledata( TableData.from_dataframe(dataframe=dataframe, table_name=table_name), primary_key, add_primary_key_column, index_attrs, )
Create a table from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: DataFrame instance to convert. :param str table_name: Table name to create. :param str primary_key: |primary_key| :param tuple index_attrs: |index_attrs| :Examples: :ref:`example-create-table-from-df`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1439-L1464
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.rollback
def rollback(self): """ .. seealso:: :py:meth:`sqlite3.Connection.rollback` """ try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("rollback: path='{}'".format(self.database_path)) self.connection.rollback()
python
def rollback(self): """ .. seealso:: :py:meth:`sqlite3.Connection.rollback` """ try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("rollback: path='{}'".format(self.database_path)) self.connection.rollback()
.. seealso:: :py:meth:`sqlite3.Connection.rollback`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1471-L1483
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.commit
def commit(self): """ .. seealso:: :py:meth:`sqlite3.Connection.commit` """ try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("commit: path='{}'".format(self.database_path)) try: self.connection.commit() except sqlite3.ProgrammingError: pass
python
def commit(self): """ .. seealso:: :py:meth:`sqlite3.Connection.commit` """ try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("commit: path='{}'".format(self.database_path)) try: self.connection.commit() except sqlite3.ProgrammingError: pass
.. seealso:: :py:meth:`sqlite3.Connection.commit`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1485-L1500
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.close
def close(self): """ Commit and close the connection. .. seealso:: :py:meth:`sqlite3.Connection.close` """ if self.__delayed_connection_path and self.__connection is None: self.__initialize_connection() return try: self.check_connection() except (SystemError, NullDatabaseConnectionError): return logger.debug("close connection to a SQLite database: path='{}'".format(self.database_path)) self.commit() self.connection.close() self.__initialize_connection()
python
def close(self): """ Commit and close the connection. .. seealso:: :py:meth:`sqlite3.Connection.close` """ if self.__delayed_connection_path and self.__connection is None: self.__initialize_connection() return try: self.check_connection() except (SystemError, NullDatabaseConnectionError): return logger.debug("close connection to a SQLite database: path='{}'".format(self.database_path)) self.commit() self.connection.close() self.__initialize_connection()
Commit and close the connection. .. seealso:: :py:meth:`sqlite3.Connection.close`
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1502-L1522
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.__verify_db_file_existence
def __verify_db_file_existence(self, database_path): """ :raises SimpleSQLite.OperationalError: If unable to open database file. """ self.__validate_db_path(database_path) if not os.path.isfile(os.path.realpath(database_path)): raise IOError("file not found: " + database_path) try: connection = sqlite3.connect(database_path) except sqlite3.OperationalError as e: raise OperationalError(e) connection.close()
python
def __verify_db_file_existence(self, database_path): """ :raises SimpleSQLite.OperationalError: If unable to open database file. """ self.__validate_db_path(database_path) if not os.path.isfile(os.path.realpath(database_path)): raise IOError("file not found: " + database_path) try: connection = sqlite3.connect(database_path) except sqlite3.OperationalError as e: raise OperationalError(e) connection.close()
:raises SimpleSQLite.OperationalError: If unable to open database file.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1546-L1560
thombashi/SimpleSQLite
simplesqlite/core.py
SimpleSQLite.__extract_col_type_from_tabledata
def __extract_col_type_from_tabledata(table_data): """ Extract data type name for each column as SQLite names. :param tabledata.TableData table_data: :return: { column_number : column_data_type } :rtype: dictionary """ typename_table = { typepy.Typecode.INTEGER: "INTEGER", typepy.Typecode.REAL_NUMBER: "REAL", typepy.Typecode.STRING: "TEXT", } return dict( [ [col_idx, typename_table.get(col_dp.typecode, "TEXT")] for col_idx, col_dp in enumerate(table_data.column_dp_list) ] )
python
def __extract_col_type_from_tabledata(table_data): """ Extract data type name for each column as SQLite names. :param tabledata.TableData table_data: :return: { column_number : column_data_type } :rtype: dictionary """ typename_table = { typepy.Typecode.INTEGER: "INTEGER", typepy.Typecode.REAL_NUMBER: "REAL", typepy.Typecode.STRING: "TEXT", } return dict( [ [col_idx, typename_table.get(col_dp.typecode, "TEXT")] for col_idx, col_dp in enumerate(table_data.column_dp_list) ] )
Extract data type name for each column as SQLite names. :param tabledata.TableData table_data: :return: { column_number : column_data_type } :rtype: dictionary
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1615-L1635
thombashi/SimpleSQLite
simplesqlite/_func.py
validate_table_name
def validate_table_name(name): """ :param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name| """ try: validate_sqlite_table_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullNameError: raise NameValidationError("table name is empty") except ValidReservedNameError: pass
python
def validate_table_name(name): """ :param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name| """ try: validate_sqlite_table_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullNameError: raise NameValidationError("table name is empty") except ValidReservedNameError: pass
:param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_func.py#L24-L37
thombashi/SimpleSQLite
simplesqlite/_func.py
validate_attr_name
def validate_attr_name(name): """ :param str name: Name to validate. :raises NameValidationError: |raises_validate_attr_name| """ try: validate_sqlite_attr_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullNameError: raise NameValidationError("attribute name is empty")
python
def validate_attr_name(name): """ :param str name: Name to validate. :raises NameValidationError: |raises_validate_attr_name| """ try: validate_sqlite_attr_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullNameError: raise NameValidationError("attribute name is empty")
:param str name: Name to validate. :raises NameValidationError: |raises_validate_attr_name|
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_func.py#L40-L51
thombashi/SimpleSQLite
simplesqlite/_func.py
append_table
def append_table(src_con, dst_con, table_name): """ Append a table from source database to destination database. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str table_name: Table name to append. :return: |True| if the append operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other. """ logger.debug( "append table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format( src_db=src_con.database_path, src_tbl=table_name, dst_db=dst_con.database_path, dst_tbl=table_name, ) ) src_con.verify_table_existence(table_name) dst_con.validate_access_permission(["w", "a"]) if dst_con.has_table(table_name): src_attrs = src_con.fetch_attr_names(table_name) dst_attrs = dst_con.fetch_attr_names(table_name) if src_attrs != dst_attrs: raise ValueError( dedent( """ source and destination attribute is different from each other src: {} dst: {} """.format( src_attrs, dst_attrs ) ) ) primary_key, index_attrs, type_hints = extract_table_metadata(src_con, table_name) dst_con.create_table_from_tabledata( src_con.select_as_tabledata(table_name, type_hints=type_hints), primary_key=primary_key, index_attrs=index_attrs, ) return True
python
def append_table(src_con, dst_con, table_name): """ Append a table from source database to destination database. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str table_name: Table name to append. :return: |True| if the append operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other. """ logger.debug( "append table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format( src_db=src_con.database_path, src_tbl=table_name, dst_db=dst_con.database_path, dst_tbl=table_name, ) ) src_con.verify_table_existence(table_name) dst_con.validate_access_permission(["w", "a"]) if dst_con.has_table(table_name): src_attrs = src_con.fetch_attr_names(table_name) dst_attrs = dst_con.fetch_attr_names(table_name) if src_attrs != dst_attrs: raise ValueError( dedent( """ source and destination attribute is different from each other src: {} dst: {} """.format( src_attrs, dst_attrs ) ) ) primary_key, index_attrs, type_hints = extract_table_metadata(src_con, table_name) dst_con.create_table_from_tabledata( src_con.select_as_tabledata(table_name, type_hints=type_hints), primary_key=primary_key, index_attrs=index_attrs, ) return True
Append a table from source database to destination database. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str table_name: Table name to append. :return: |True| if the append operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_func.py#L54-L105
thombashi/SimpleSQLite
simplesqlite/_func.py
copy_table
def copy_table(src_con, dst_con, src_table_name, dst_table_name, is_overwrite=True): """ Copy a table from source to destination. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str src_table_name: Source table name to copy. :param str dst_table_name: Destination table name. :param bool is_overwrite: If |True|, overwrite existing table. :return: |True| if the copy operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other. """ logger.debug( "copy table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format( src_db=src_con.database_path, src_tbl=src_table_name, dst_db=dst_con.database_path, dst_tbl=dst_table_name, ) ) src_con.verify_table_existence(src_table_name) dst_con.validate_access_permission(["w", "a"]) if dst_con.has_table(dst_table_name): if is_overwrite: dst_con.drop_table(dst_table_name) else: logger.error( "failed to copy table: the table already exists " "(src_table={}, dst_table={})".format(src_table_name, dst_table_name) ) return False primary_key, index_attrs, _ = extract_table_metadata(src_con, src_table_name) result = src_con.select(select="*", table_name=src_table_name) if result is None: return False dst_con.create_table_from_data_matrix( dst_table_name, src_con.fetch_attr_names(src_table_name), result.fetchall(), primary_key=primary_key, index_attrs=index_attrs, ) return True
python
def copy_table(src_con, dst_con, src_table_name, dst_table_name, is_overwrite=True): """ Copy a table from source to destination. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str src_table_name: Source table name to copy. :param str dst_table_name: Destination table name. :param bool is_overwrite: If |True|, overwrite existing table. :return: |True| if the copy operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other. """ logger.debug( "copy table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format( src_db=src_con.database_path, src_tbl=src_table_name, dst_db=dst_con.database_path, dst_tbl=dst_table_name, ) ) src_con.verify_table_existence(src_table_name) dst_con.validate_access_permission(["w", "a"]) if dst_con.has_table(dst_table_name): if is_overwrite: dst_con.drop_table(dst_table_name) else: logger.error( "failed to copy table: the table already exists " "(src_table={}, dst_table={})".format(src_table_name, dst_table_name) ) return False primary_key, index_attrs, _ = extract_table_metadata(src_con, src_table_name) result = src_con.select(select="*", table_name=src_table_name) if result is None: return False dst_con.create_table_from_data_matrix( dst_table_name, src_con.fetch_attr_names(src_table_name), result.fetchall(), primary_key=primary_key, index_attrs=index_attrs, ) return True
Copy a table from source to destination. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str src_table_name: Source table name to copy. :param str dst_table_name: Destination table name. :param bool is_overwrite: If |True|, overwrite existing table. :return: |True| if the copy operation succeed. :rtype: bool :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| :raises ValueError: If attributes of the table are different from each other.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_func.py#L108-L161
thombashi/SimpleSQLite
simplesqlite/_validator.py
validate_sqlite_table_name
def validate_sqlite_table_name(name): """ :param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as a table name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as a table name. """ if not name: raise NullNameError("null name") if __RE_INVALID_CHARS.search(name): raise InvalidCharError("unprintable character found") name = name.upper() if name in __SQLITE_INVALID_RESERVED_KEYWORDS_TABLE: raise InvalidReservedNameError("'{:s}' is a reserved keyword by sqlite".format(name)) if name in __SQLITE_VALID_RESERVED_KEYWORDS_TABLE: raise ValidReservedNameError("'{:s}' is a reserved keyword by sqlite".format(name))
python
def validate_sqlite_table_name(name): """ :param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as a table name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as a table name. """ if not name: raise NullNameError("null name") if __RE_INVALID_CHARS.search(name): raise InvalidCharError("unprintable character found") name = name.upper() if name in __SQLITE_INVALID_RESERVED_KEYWORDS_TABLE: raise InvalidReservedNameError("'{:s}' is a reserved keyword by sqlite".format(name)) if name in __SQLITE_VALID_RESERVED_KEYWORDS_TABLE: raise ValidReservedNameError("'{:s}' is a reserved keyword by sqlite".format(name))
:param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as a table name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as a table name.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_validator.py#L155-L181
thombashi/SimpleSQLite
simplesqlite/_validator.py
validate_sqlite_attr_name
def validate_sqlite_attr_name(name): """ :param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as an attribute name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as an attribute name. """ if not name: raise NullNameError("null name") if __RE_INVALID_CHARS.search(name): raise InvalidCharError("unprintable character found") name = name.upper() if name in __SQLITE_INVALID_RESERVED_KEYWORDS_ATTR: raise InvalidReservedNameError("'{}' is a reserved keyword by sqlite".format(name)) if name in __SQLITE_VALID_RESERVED_KEYWORDS_ATTR: raise ValidReservedNameError("'{}' is a reserved keyword by sqlite".format(name))
python
def validate_sqlite_attr_name(name): """ :param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as an attribute name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as an attribute name. """ if not name: raise NullNameError("null name") if __RE_INVALID_CHARS.search(name): raise InvalidCharError("unprintable character found") name = name.upper() if name in __SQLITE_INVALID_RESERVED_KEYWORDS_ATTR: raise InvalidReservedNameError("'{}' is a reserved keyword by sqlite".format(name)) if name in __SQLITE_VALID_RESERVED_KEYWORDS_ATTR: raise ValidReservedNameError("'{}' is a reserved keyword by sqlite".format(name))
:param str name: Name to validate. :raises pathvalidate.NullNameError: If the ``name`` is empty. :raises pathvalidate.InvalidCharError: If the ``name`` includes unprintable character(s). :raises pathvalidate.InvalidReservedNameError: |raises_sqlite_keywords| And invalid as an attribute name. :raises pathvalidate.ValidReservedNameError: |raises_sqlite_keywords| However, valid as an attribute name.
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/_validator.py#L184-L210
alorence/django-modern-rpc
modernrpc/compat.py
_generic_convert_string
def _generic_convert_string(v, from_type, to_type, encoding): """ Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: The value to convert :param from_type: The original string type to convert :param to_type: The target string type to convert to :param encoding: When :return: """ assert six.PY2, "This function should be used with Python 2 only" assert from_type != to_type if from_type == six.binary_type and isinstance(v, six.binary_type): return six.text_type(v, encoding) elif from_type == six.text_type and isinstance(v, six.text_type): return v.encode(encoding) elif isinstance(v, (list, tuple, set)): return type(v)([_generic_convert_string(element, from_type, to_type, encoding) for element in v]) elif isinstance(v, dict): return {k: _generic_convert_string(v, from_type, to_type, encoding) for k, v in v.iteritems()} return v
python
def _generic_convert_string(v, from_type, to_type, encoding): """ Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: The value to convert :param from_type: The original string type to convert :param to_type: The target string type to convert to :param encoding: When :return: """ assert six.PY2, "This function should be used with Python 2 only" assert from_type != to_type if from_type == six.binary_type and isinstance(v, six.binary_type): return six.text_type(v, encoding) elif from_type == six.text_type and isinstance(v, six.text_type): return v.encode(encoding) elif isinstance(v, (list, tuple, set)): return type(v)([_generic_convert_string(element, from_type, to_type, encoding) for element in v]) elif isinstance(v, dict): return {k: _generic_convert_string(v, from_type, to_type, encoding) for k, v in v.iteritems()} return v
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: The value to convert :param from_type: The original string type to convert :param to_type: The target string type to convert to :param encoding: When :return:
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/compat.py#L7-L35
alorence/django-modern-rpc
modernrpc/compat.py
standardize_strings
def standardize_strings(arg, strtype=settings.MODERNRPC_PY2_STR_TYPE, encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and MODERNRPC_PY2_STR_ENCODING settings. """ assert six.PY2, "This function should be used with Python 2 only" if not strtype: return arg if strtype == six.binary_type or strtype == 'str': # We want to convert from unicode to str return _generic_convert_string(arg, six.text_type, six.binary_type, encoding) elif strtype == six.text_type or strtype == 'unicode': # We want to convert from str to unicode return _generic_convert_string(arg, six.binary_type, six.text_type, encoding) raise TypeError('standardize_strings() called with an invalid strtype: "{}". Allowed values: str or unicode' .format(repr(strtype)))
python
def standardize_strings(arg, strtype=settings.MODERNRPC_PY2_STR_TYPE, encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and MODERNRPC_PY2_STR_ENCODING settings. """ assert six.PY2, "This function should be used with Python 2 only" if not strtype: return arg if strtype == six.binary_type or strtype == 'str': # We want to convert from unicode to str return _generic_convert_string(arg, six.text_type, six.binary_type, encoding) elif strtype == six.text_type or strtype == 'unicode': # We want to convert from str to unicode return _generic_convert_string(arg, six.binary_type, six.text_type, encoding) raise TypeError('standardize_strings() called with an invalid strtype: "{}". Allowed values: str or unicode' .format(repr(strtype)))
Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and MODERNRPC_PY2_STR_ENCODING settings.
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/compat.py#L38-L57
alorence/django-modern-rpc
modernrpc/helpers.py
get_builtin_date
def get_builtin_date(date, date_format="%Y-%m-%dT%H:%M:%S", raise_exception=False): """ Try to convert a date to a builtin instance of ``datetime.datetime``. The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime`` instance. The returned object is a ``datetime.datetime``. :param date: The date object to convert. :param date_format: If the given date is a str, format is passed to strptime to parse it :param raise_exception: If set to True, an exception will be raised if the input string cannot be parsed :return: A valid ``datetime.datetime`` instance """ if isinstance(date, datetime.datetime): # Default XML-RPC handler is configured to decode dateTime.iso8601 type # to builtin datetime.datetim instance return date elif isinstance(date, xmlrpc_client.DateTime): # If constant settings.MODERNRPC_XMLRPC_USE_BUILTIN_TYPES has been set to True # the date is decoded as DateTime object return datetime.datetime.strptime(date.value, "%Y%m%dT%H:%M:%S") else: # If date is given as str (or unicode for python 2) # This is the normal behavior for JSON-RPC try: return datetime.datetime.strptime(date, date_format) except ValueError: if raise_exception: raise else: return None
python
def get_builtin_date(date, date_format="%Y-%m-%dT%H:%M:%S", raise_exception=False): """ Try to convert a date to a builtin instance of ``datetime.datetime``. The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime`` instance. The returned object is a ``datetime.datetime``. :param date: The date object to convert. :param date_format: If the given date is a str, format is passed to strptime to parse it :param raise_exception: If set to True, an exception will be raised if the input string cannot be parsed :return: A valid ``datetime.datetime`` instance """ if isinstance(date, datetime.datetime): # Default XML-RPC handler is configured to decode dateTime.iso8601 type # to builtin datetime.datetim instance return date elif isinstance(date, xmlrpc_client.DateTime): # If constant settings.MODERNRPC_XMLRPC_USE_BUILTIN_TYPES has been set to True # the date is decoded as DateTime object return datetime.datetime.strptime(date.value, "%Y%m%dT%H:%M:%S") else: # If date is given as str (or unicode for python 2) # This is the normal behavior for JSON-RPC try: return datetime.datetime.strptime(date, date_format) except ValueError: if raise_exception: raise else: return None
Try to convert a date to a builtin instance of ``datetime.datetime``. The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime`` instance. The returned object is a ``datetime.datetime``. :param date: The date object to convert. :param date_format: If the given date is a str, format is passed to strptime to parse it :param raise_exception: If set to True, an exception will be raised if the input string cannot be parsed :return: A valid ``datetime.datetime`` instance
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/helpers.py#L7-L35
alorence/django-modern-rpc
modernrpc/auth/__init__.py
set_authentication_predicate
def set_authentication_predicate(predicate, params=()): """ Assign a new authentication predicate to an RPC method. This is the most generic decorator used to implement authentication. Predicate is a standard function with the following signature: .. code:: python def my_predicate(request, *params): # Inspect request and extract required information if <condition>: # The condition to execute the method are met return True return False :param predicate: :param params: :return: """ def wrapper(rpc_method): if hasattr(rpc_method, 'modernrpc_auth_predicates'): rpc_method.modernrpc_auth_predicates.append(predicate) rpc_method.modernrpc_auth_predicates_params.append(params) else: rpc_method.modernrpc_auth_predicates = [predicate] rpc_method.modernrpc_auth_predicates_params = [params] return rpc_method return wrapper
python
def set_authentication_predicate(predicate, params=()): """ Assign a new authentication predicate to an RPC method. This is the most generic decorator used to implement authentication. Predicate is a standard function with the following signature: .. code:: python def my_predicate(request, *params): # Inspect request and extract required information if <condition>: # The condition to execute the method are met return True return False :param predicate: :param params: :return: """ def wrapper(rpc_method): if hasattr(rpc_method, 'modernrpc_auth_predicates'): rpc_method.modernrpc_auth_predicates.append(predicate) rpc_method.modernrpc_auth_predicates_params.append(params) else: rpc_method.modernrpc_auth_predicates = [predicate] rpc_method.modernrpc_auth_predicates_params = [params] return rpc_method return wrapper
Assign a new authentication predicate to an RPC method. This is the most generic decorator used to implement authentication. Predicate is a standard function with the following signature: .. code:: python def my_predicate(request, *params): # Inspect request and extract required information if <condition>: # The condition to execute the method are met return True return False :param predicate: :param params: :return:
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/__init__.py#L10-L43
alorence/django-modern-rpc
modernrpc/auth/__init__.py
user_in_group
def user_in_group(user, group): """Returns True if the given user is in given group""" if isinstance(group, Group): return user_is_superuser(user) or group in user.groups.all() elif isinstance(group, six.string_types): return user_is_superuser(user) or user.groups.filter(name=group).exists() raise TypeError("'group' argument must be a string or a Group instance")
python
def user_in_group(user, group): """Returns True if the given user is in given group""" if isinstance(group, Group): return user_is_superuser(user) or group in user.groups.all() elif isinstance(group, six.string_types): return user_is_superuser(user) or user.groups.filter(name=group).exists() raise TypeError("'group' argument must be a string or a Group instance")
Returns True if the given user is in given group
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/__init__.py#L77-L83
alorence/django-modern-rpc
modernrpc/auth/__init__.py
user_in_any_group
def user_in_any_group(user, groups): """Returns True if the given user is in at least 1 of the given groups""" return user_is_superuser(user) or any(user_in_group(user, group) for group in groups)
python
def user_in_any_group(user, groups): """Returns True if the given user is in at least 1 of the given groups""" return user_is_superuser(user) or any(user_in_group(user, group) for group in groups)
Returns True if the given user is in at least 1 of the given groups
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/__init__.py#L86-L88
alorence/django-modern-rpc
modernrpc/auth/__init__.py
user_in_all_groups
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
python
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
Returns True if the given user is in all given groups
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/__init__.py#L91-L93
alorence/django-modern-rpc
modernrpc/views.py
RPCEntryPoint.get_handler_classes
def get_handler_classes(self): """Return the list of handlers to use when receiving RPC requests.""" handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS] if self.protocol == ALL: return handler_classes else: return [cls for cls in handler_classes if cls.protocol in ensure_sequence(self.protocol)]
python
def get_handler_classes(self): """Return the list of handlers to use when receiving RPC requests.""" handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS] if self.protocol == ALL: return handler_classes else: return [cls for cls in handler_classes if cls.protocol in ensure_sequence(self.protocol)]
Return the list of handlers to use when receiving RPC requests.
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/views.py#L57-L65
alorence/django-modern-rpc
modernrpc/views.py
RPCEntryPoint.post
def post(self, request, *args, **kwargs): """ Handle a XML-RPC or JSON-RPC request. :param request: Incoming request :param args: Additional arguments :param kwargs: Additional named arguments :return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on the incoming request """ logger.debug('RPC request received...') for handler_cls in self.get_handler_classes(): handler = handler_cls(request, self.entry_point) try: if not handler.can_handle(): continue logger.debug('Request will be handled by {}'.format(handler_cls.__name__)) result = handler.process_request() return handler.result_success(result) except AuthenticationFailed as e: # Customize HttpResponse instance used when AuthenticationFailed was raised logger.warning(e) return handler.result_error(e, HttpResponseForbidden) except RPCException as e: logger.warning('RPC exception: {}'.format(e), exc_info=settings.MODERNRPC_LOG_EXCEPTIONS) return handler.result_error(e) except Exception as e: logger.error('Exception raised from a RPC method: "{}"'.format(e), exc_info=settings.MODERNRPC_LOG_EXCEPTIONS) return handler.result_error(RPCInternalError(str(e))) logger.error('Unable to handle incoming request.') return HttpResponse('Unable to handle your request. Please ensure you called the right entry point. If not, ' 'this could be a server error.')
python
def post(self, request, *args, **kwargs): """ Handle a XML-RPC or JSON-RPC request. :param request: Incoming request :param args: Additional arguments :param kwargs: Additional named arguments :return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on the incoming request """ logger.debug('RPC request received...') for handler_cls in self.get_handler_classes(): handler = handler_cls(request, self.entry_point) try: if not handler.can_handle(): continue logger.debug('Request will be handled by {}'.format(handler_cls.__name__)) result = handler.process_request() return handler.result_success(result) except AuthenticationFailed as e: # Customize HttpResponse instance used when AuthenticationFailed was raised logger.warning(e) return handler.result_error(e, HttpResponseForbidden) except RPCException as e: logger.warning('RPC exception: {}'.format(e), exc_info=settings.MODERNRPC_LOG_EXCEPTIONS) return handler.result_error(e) except Exception as e: logger.error('Exception raised from a RPC method: "{}"'.format(e), exc_info=settings.MODERNRPC_LOG_EXCEPTIONS) return handler.result_error(RPCInternalError(str(e))) logger.error('Unable to handle incoming request.') return HttpResponse('Unable to handle your request. Please ensure you called the right entry point. If not, ' 'this could be a server error.')
Handle a XML-RPC or JSON-RPC request. :param request: Incoming request :param args: Additional arguments :param kwargs: Additional named arguments :return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on the incoming request
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/views.py#L67-L110
alorence/django-modern-rpc
modernrpc/views.py
RPCEntryPoint.get_context_data
def get_context_data(self, **kwargs): """Update context data with list of RPC methods of the current entry point. Will be used to display methods documentation page""" kwargs.update({ 'methods': registry.get_all_methods(self.entry_point, sort_methods=True), }) return super(RPCEntryPoint, self).get_context_data(**kwargs)
python
def get_context_data(self, **kwargs): """Update context data with list of RPC methods of the current entry point. Will be used to display methods documentation page""" kwargs.update({ 'methods': registry.get_all_methods(self.entry_point, sort_methods=True), }) return super(RPCEntryPoint, self).get_context_data(**kwargs)
Update context data with list of RPC methods of the current entry point. Will be used to display methods documentation page
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/views.py#L112-L118
alorence/django-modern-rpc
modernrpc/apps.py
ModernRpcConfig.rpc_methods_registration
def rpc_methods_registration(): """Look into each module listed in settings.MODERNRPC_METHODS_MODULES, import each module and register functions annotated with @rpc_method decorator in the registry""" # In previous version, django-modern-rpc used the django cache system to store methods registry. # It is useless now, so clean the cache from old data clean_old_cache_content() # For security (and unit tests), make sure the registry is empty before registering rpc methods registry.reset() if not settings.MODERNRPC_METHODS_MODULES: # settings.MODERNRPC_METHODS_MODULES is undefined or empty, but we already notified user # with check_required_settings_defined() function. See http://docs.djangoproject.com/en/1.10/topics/checks/ return # Lookup content of MODERNRPC_METHODS_MODULES, and add the module containing system methods for module_name in settings.MODERNRPC_METHODS_MODULES + ['modernrpc.system_methods']: try: # Import the module in current scope rpc_module = import_module(module_name) except ImportError: msg = 'Unable to load module "{}" declared in settings.MODERNRPC_METHODS_MODULES. Please ensure ' \ 'it is available and doesn\'t contains any error'.format(module_name) warnings.warn(msg, category=Warning) continue # Lookup all global functions in module for _, func in inspect.getmembers(rpc_module, inspect.isfunction): # And register only functions with attribute 'modernrpc_enabled' defined to True if getattr(func, 'modernrpc_enabled', False): registry.register_method(func) logger.info('django-modern-rpc initialized: {} RPC methods registered'.format(registry.total_count()))
python
def rpc_methods_registration(): """Look into each module listed in settings.MODERNRPC_METHODS_MODULES, import each module and register functions annotated with @rpc_method decorator in the registry""" # In previous version, django-modern-rpc used the django cache system to store methods registry. # It is useless now, so clean the cache from old data clean_old_cache_content() # For security (and unit tests), make sure the registry is empty before registering rpc methods registry.reset() if not settings.MODERNRPC_METHODS_MODULES: # settings.MODERNRPC_METHODS_MODULES is undefined or empty, but we already notified user # with check_required_settings_defined() function. See http://docs.djangoproject.com/en/1.10/topics/checks/ return # Lookup content of MODERNRPC_METHODS_MODULES, and add the module containing system methods for module_name in settings.MODERNRPC_METHODS_MODULES + ['modernrpc.system_methods']: try: # Import the module in current scope rpc_module = import_module(module_name) except ImportError: msg = 'Unable to load module "{}" declared in settings.MODERNRPC_METHODS_MODULES. Please ensure ' \ 'it is available and doesn\'t contains any error'.format(module_name) warnings.warn(msg, category=Warning) continue # Lookup all global functions in module for _, func in inspect.getmembers(rpc_module, inspect.isfunction): # And register only functions with attribute 'modernrpc_enabled' defined to True if getattr(func, 'modernrpc_enabled', False): registry.register_method(func) logger.info('django-modern-rpc initialized: {} RPC methods registered'.format(registry.total_count()))
Look into each module listed in settings.MODERNRPC_METHODS_MODULES, import each module and register functions annotated with @rpc_method decorator in the registry
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/apps.py#L43-L77
alorence/django-modern-rpc
modernrpc/auth/basic.py
http_basic_auth_get_user
def http_basic_auth_get_user(request): """Inspect the given request to find a logged user. If not found, the header HTTP_AUTHORIZATION is read for 'Basic Auth' login and password, and try to authenticate against default UserModel. Always return a User instance (possibly anonymous, meaning authentication failed)""" try: # If standard auth middleware already authenticated a user, use it if user_is_authenticated(request.user): return request.user except AttributeError: pass # This was grabbed from https://www.djangosnippets.org/snippets/243/ # Thanks to http://stackoverflow.com/a/1087736/1887976 if 'HTTP_AUTHORIZATION' in request.META: auth_data = request.META['HTTP_AUTHORIZATION'].split() if len(auth_data) == 2 and auth_data[0].lower() == "basic": uname, passwd = base64.b64decode(auth_data[1]).decode('utf-8').split(':') django_user = authenticate(username=uname, password=passwd) if django_user is not None: login(request, django_user) # In all cases, return the current request's user (may be anonymous user if no login succeed) try: return request.user except AttributeError: return AnonymousUser()
python
def http_basic_auth_get_user(request): """Inspect the given request to find a logged user. If not found, the header HTTP_AUTHORIZATION is read for 'Basic Auth' login and password, and try to authenticate against default UserModel. Always return a User instance (possibly anonymous, meaning authentication failed)""" try: # If standard auth middleware already authenticated a user, use it if user_is_authenticated(request.user): return request.user except AttributeError: pass # This was grabbed from https://www.djangosnippets.org/snippets/243/ # Thanks to http://stackoverflow.com/a/1087736/1887976 if 'HTTP_AUTHORIZATION' in request.META: auth_data = request.META['HTTP_AUTHORIZATION'].split() if len(auth_data) == 2 and auth_data[0].lower() == "basic": uname, passwd = base64.b64decode(auth_data[1]).decode('utf-8').split(':') django_user = authenticate(username=uname, password=passwd) if django_user is not None: login(request, django_user) # In all cases, return the current request's user (may be anonymous user if no login succeed) try: return request.user except AttributeError: return AnonymousUser()
Inspect the given request to find a logged user. If not found, the header HTTP_AUTHORIZATION is read for 'Basic Auth' login and password, and try to authenticate against default UserModel. Always return a User instance (possibly anonymous, meaning authentication failed)
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L24-L50
alorence/django-modern-rpc
modernrpc/auth/basic.py
http_basic_auth_login_required
def http_basic_auth_login_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged users""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated]) # If @http_basic_auth_login_required() is used (with parenthesis) if func is None: return wrapper # If @http_basic_auth_login_required is used without parenthesis return wrapper(func)
python
def http_basic_auth_login_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged users""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated]) # If @http_basic_auth_login_required() is used (with parenthesis) if func is None: return wrapper # If @http_basic_auth_login_required is used without parenthesis return wrapper(func)
Decorator. Use it to specify a RPC method is available only to logged users
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L54-L64
alorence/django-modern-rpc
modernrpc/auth/basic.py
http_basic_auth_superuser_required
def http_basic_auth_superuser_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged superusers""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser]) # If @http_basic_auth_superuser_required() is used (with parenthesis) if func is None: return wrapper # If @http_basic_auth_superuser_required is used without parenthesis return wrapper(func)
python
def http_basic_auth_superuser_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged superusers""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser]) # If @http_basic_auth_superuser_required() is used (with parenthesis) if func is None: return wrapper # If @http_basic_auth_superuser_required is used without parenthesis return wrapper(func)
Decorator. Use it to specify a RPC method is available only to logged superusers
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L68-L78
alorence/django-modern-rpc
modernrpc/auth/basic.py
http_basic_auth_permissions_required
def http_basic_auth_permissions_required(permissions): """Decorator. Use it to specify a RPC method is available only to logged users with given permissions""" if isinstance(permissions, six.string_types): return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_perm, permissions]) else: return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_all_perms, permissions])
python
def http_basic_auth_permissions_required(permissions): """Decorator. Use it to specify a RPC method is available only to logged users with given permissions""" if isinstance(permissions, six.string_types): return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_perm, permissions]) else: return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_all_perms, permissions])
Decorator. Use it to specify a RPC method is available only to logged users with given permissions
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L82-L88
alorence/django-modern-rpc
modernrpc/auth/basic.py
http_basic_auth_group_member_required
def http_basic_auth_group_member_required(groups): """Decorator. Use it to specify a RPC method is available only to logged users with given permissions""" if isinstance(groups, six.string_types): # Check user is in a group return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_group, groups]) else: # Check user is in many group return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_any_group, groups])
python
def http_basic_auth_group_member_required(groups): """Decorator. Use it to specify a RPC method is available only to logged users with given permissions""" if isinstance(groups, six.string_types): # Check user is in a group return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_group, groups]) else: # Check user is in many group return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_any_group, groups])
Decorator. Use it to specify a RPC method is available only to logged users with given permissions
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L98-L106
alorence/django-modern-rpc
modernrpc/core.py
rpc_method
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL, str_standardization=settings.MODERNRPC_PY2_STR_TYPE, str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Mark a standard python function as RPC method. All arguments are optional :param func: A standard function :param name: Used as RPC method name instead of original function name :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points :param protocol: Default: ALL. Used to limit usage of the RPC method for a specific protocol (JSONRPC or XMLRPC) :param str_standardization: Default: settings.MODERNRPC_PY2_STR_TYPE. Configure string standardization on python 2. Ignored on python 3. :param str_standardization_encoding: Default: settings.MODERNRPC_PY2_STR_ENCODING. Configure the encoding used to perform string standardization conversion. Ignored on python 3. :type name: str :type entry_point: str :type protocol: str :type str_standardization: type str or unicode :type str_standardization_encoding: str """ def decorated(_func): _func.modernrpc_enabled = True _func.modernrpc_name = name or _func.__name__ _func.modernrpc_entry_point = entry_point _func.modernrpc_protocol = protocol _func.str_standardization = str_standardization _func.str_standardization_encoding = str_standardization_encoding return _func # If @rpc_method() is used with parenthesis (with or without argument) if func is None: return decorated # If @rpc_method is used without parenthesis return decorated(func)
python
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL, str_standardization=settings.MODERNRPC_PY2_STR_TYPE, str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Mark a standard python function as RPC method. All arguments are optional :param func: A standard function :param name: Used as RPC method name instead of original function name :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points :param protocol: Default: ALL. Used to limit usage of the RPC method for a specific protocol (JSONRPC or XMLRPC) :param str_standardization: Default: settings.MODERNRPC_PY2_STR_TYPE. Configure string standardization on python 2. Ignored on python 3. :param str_standardization_encoding: Default: settings.MODERNRPC_PY2_STR_ENCODING. Configure the encoding used to perform string standardization conversion. Ignored on python 3. :type name: str :type entry_point: str :type protocol: str :type str_standardization: type str or unicode :type str_standardization_encoding: str """ def decorated(_func): _func.modernrpc_enabled = True _func.modernrpc_name = name or _func.__name__ _func.modernrpc_entry_point = entry_point _func.modernrpc_protocol = protocol _func.str_standardization = str_standardization _func.str_standardization_encoding = str_standardization_encoding return _func # If @rpc_method() is used with parenthesis (with or without argument) if func is None: return decorated # If @rpc_method is used without parenthesis return decorated(func)
Mark a standard python function as RPC method. All arguments are optional :param func: A standard function :param name: Used as RPC method name instead of original function name :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points :param protocol: Default: ALL. Used to limit usage of the RPC method for a specific protocol (JSONRPC or XMLRPC) :param str_standardization: Default: settings.MODERNRPC_PY2_STR_TYPE. Configure string standardization on python 2. Ignored on python 3. :param str_standardization_encoding: Default: settings.MODERNRPC_PY2_STR_ENCODING. Configure the encoding used to perform string standardization conversion. Ignored on python 3. :type name: str :type entry_point: str :type protocol: str :type str_standardization: type str or unicode :type str_standardization_encoding: str
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L330-L369
alorence/django-modern-rpc
modernrpc/core.py
get_all_method_names
def get_all_method_names(entry_point=ALL, protocol=ALL, sort_methods=False): """For backward compatibility. Use registry.get_all_method_names() instead (with same arguments)""" return registry.get_all_method_names(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods)
python
def get_all_method_names(entry_point=ALL, protocol=ALL, sort_methods=False): """For backward compatibility. Use registry.get_all_method_names() instead (with same arguments)""" return registry.get_all_method_names(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods)
For backward compatibility. Use registry.get_all_method_names() instead (with same arguments)
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L380-L382
alorence/django-modern-rpc
modernrpc/core.py
get_all_methods
def get_all_methods(entry_point=ALL, protocol=ALL, sort_methods=False): """For backward compatibility. Use registry.get_all_methods() instead (with same arguments)""" return registry.get_all_methods(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods)
python
def get_all_methods(entry_point=ALL, protocol=ALL, sort_methods=False): """For backward compatibility. Use registry.get_all_methods() instead (with same arguments)""" return registry.get_all_methods(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods)
For backward compatibility. Use registry.get_all_methods() instead (with same arguments)
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L385-L387
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.parse_docstring
def parse_docstring(self, content): """ Parse the given full docstring, and extract method description, arguments, and return documentation. This method try to find arguments description and types, and put the information in "args_doc" and "signature" members. Also parse return type and description, and put the information in "return_doc" member. All other lines are added to the returned string :param content: The full docstring :type content: str :return: The parsed method description :rtype: str """ if not content: return raw_docstring = '' # We use the helper defined in django admindocs app to remove indentation chars from docstring, # and parse it as title, body, metadata. We don't use metadata for now. docstring = trim_docstring(content) for line in docstring.split('\n'): # Empty line if not line: raw_docstring += '\n' continue param_match = PARAM_REXP.match(line) if param_match: param_name, description = param_match.group(1, 2) if param_name == 'kwargs': continue doc = self.args_doc.setdefault(param_name, {}) doc['text'] = description continue param_type_match = PARAM_TYPE_REXP.match(line) if param_type_match: param_name, param_type = param_type_match.group(1, 2) if param_name == 'kwargs': continue doc = self.args_doc.setdefault(param_name, {}) doc['type'] = param_type self.signature.append(param_type) continue return_match = RETURN_REXP.match(line) if return_match: return_description = return_match.group(1) self.return_doc['text'] = return_description continue return_type_match = RETURN_TYPE_REXP.match(line) if return_type_match: return_description = return_type_match.group(1) self.return_doc['type'] = return_description self.signature.insert(0, return_description) continue # Line doesn't match with known args/return regular expressions, # add the line to raw help text raw_docstring += line + '\n' return raw_docstring
python
def parse_docstring(self, content): """ Parse the given full docstring, and extract method description, arguments, and return documentation. This method try to find arguments description and types, and put the information in "args_doc" and "signature" members. Also parse return type and description, and put the information in "return_doc" member. All other lines are added to the returned string :param content: The full docstring :type content: str :return: The parsed method description :rtype: str """ if not content: return raw_docstring = '' # We use the helper defined in django admindocs app to remove indentation chars from docstring, # and parse it as title, body, metadata. We don't use metadata for now. docstring = trim_docstring(content) for line in docstring.split('\n'): # Empty line if not line: raw_docstring += '\n' continue param_match = PARAM_REXP.match(line) if param_match: param_name, description = param_match.group(1, 2) if param_name == 'kwargs': continue doc = self.args_doc.setdefault(param_name, {}) doc['text'] = description continue param_type_match = PARAM_TYPE_REXP.match(line) if param_type_match: param_name, param_type = param_type_match.group(1, 2) if param_name == 'kwargs': continue doc = self.args_doc.setdefault(param_name, {}) doc['type'] = param_type self.signature.append(param_type) continue return_match = RETURN_REXP.match(line) if return_match: return_description = return_match.group(1) self.return_doc['text'] = return_description continue return_type_match = RETURN_TYPE_REXP.match(line) if return_type_match: return_description = return_type_match.group(1) self.return_doc['type'] = return_description self.signature.insert(0, return_description) continue # Line doesn't match with known args/return regular expressions, # add the line to raw help text raw_docstring += line + '\n' return raw_docstring
Parse the given full docstring, and extract method description, arguments, and return documentation. This method try to find arguments description and types, and put the information in "args_doc" and "signature" members. Also parse return type and description, and put the information in "return_doc" member. All other lines are added to the returned string :param content: The full docstring :type content: str :return: The parsed method description :rtype: str
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L92-L159
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.html_doc
def html_doc(self): """Methods docstring, as HTML""" if not self.raw_docstring: result = '' elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'): from docutils.core import publish_parts result = publish_parts(self.raw_docstring, writer_name='html')['body'] elif settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'): import markdown result = markdown.markdown(self.raw_docstring) else: result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' ')) return result
python
def html_doc(self): """Methods docstring, as HTML""" if not self.raw_docstring: result = '' elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'): from docutils.core import publish_parts result = publish_parts(self.raw_docstring, writer_name='html')['body'] elif settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'): import markdown result = markdown.markdown(self.raw_docstring) else: result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' ')) return result
Methods docstring, as HTML
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L162-L178
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.check_permissions
def check_permissions(self, request): """Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)""" if not self.predicates: return True # All registered authentication predicates must return True return all( predicate(request, *self.predicates_params[i]) for i, predicate in enumerate(self.predicates) )
python
def check_permissions(self, request): """Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)""" if not self.predicates: return True # All registered authentication predicates must return True return all( predicate(request, *self.predicates_params[i]) for i, predicate in enumerate(self.predicates) )
Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L180-L192
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.available_for_protocol
def available_for_protocol(self, protocol): """Check if the current function can be executed from a request defining the given protocol""" if self.protocol == ALL or protocol == ALL: return True return protocol in ensure_sequence(self.protocol)
python
def available_for_protocol(self, protocol): """Check if the current function can be executed from a request defining the given protocol""" if self.protocol == ALL or protocol == ALL: return True return protocol in ensure_sequence(self.protocol)
Check if the current function can be executed from a request defining the given protocol
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L194-L199
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.available_for_entry_point
def available_for_entry_point(self, entry_point): """Check if the current function can be executed from a request to the given entry point""" if self.entry_point == ALL or entry_point == ALL: return True return entry_point in ensure_sequence(self.entry_point)
python
def available_for_entry_point(self, entry_point): """Check if the current function can be executed from a request to the given entry point""" if self.entry_point == ALL or entry_point == ALL: return True return entry_point in ensure_sequence(self.entry_point)
Check if the current function can be executed from a request to the given entry point
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L201-L206
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.is_valid_for
def is_valid_for(self, entry_point, protocol): """Check if the current function can be executed from a request to the given entry point and with the given protocol""" return self.available_for_entry_point(entry_point) and self.available_for_protocol(protocol)
python
def is_valid_for(self, entry_point, protocol): """Check if the current function can be executed from a request to the given entry point and with the given protocol""" return self.available_for_entry_point(entry_point) and self.available_for_protocol(protocol)
Check if the current function can be executed from a request to the given entry point and with the given protocol
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L208-L211
alorence/django-modern-rpc
modernrpc/core.py
RPCMethod.is_return_doc_available
def is_return_doc_available(self): """Returns True if this method's return is documented""" return bool(self.return_doc and (self.return_doc.get('text') or self.return_doc.get('type')))
python
def is_return_doc_available(self): """Returns True if this method's return is documented""" return bool(self.return_doc and (self.return_doc.get('text') or self.return_doc.get('type')))
Returns True if this method's return is documented
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L228-L230
alorence/django-modern-rpc
modernrpc/core.py
_RPCRegistry.register_method
def register_method(self, func): """ Register a function to be available as RPC method. The given function will be inspected to find external_name, protocol and entry_point values set by the decorator @rpc_method. :param func: A function previously decorated using @rpc_method :return: The name of registered method """ if not getattr(func, 'modernrpc_enabled', False): raise ImproperlyConfigured('Error: trying to register {} as RPC method, but it has not been decorated.' .format(func.__name__)) # Define the external name of the function name = getattr(func, 'modernrpc_name', func.__name__) logger.debug('Register RPC method "{}"'.format(name)) if name.startswith('rpc.'): raise ImproperlyConfigured('According to RPC standard, method names starting with "rpc." are reserved for ' 'system extensions and must not be used. See ' 'http://www.jsonrpc.org/specification#extensions for more information.') # Encapsulate the function in a RPCMethod object method = RPCMethod(func) # Ensure method names are unique in the registry existing_method = self.get_method(method.name, ALL, ALL) if existing_method is not None: # Trying to register many times the same function is OK, because if a method is decorated # with @rpc_method(), it could be imported in different places of the code if method == existing_method: return method.name # But if we try to use the same name to register 2 different methods, we # must inform the developer there is an error in the code else: raise ImproperlyConfigured("A RPC method with name {} has already been registered".format(method.name)) # Store the method self._registry[method.name] = method logger.debug('Method registered. len(registry): {}'.format(len(self._registry))) return method.name
python
def register_method(self, func): """ Register a function to be available as RPC method. The given function will be inspected to find external_name, protocol and entry_point values set by the decorator @rpc_method. :param func: A function previously decorated using @rpc_method :return: The name of registered method """ if not getattr(func, 'modernrpc_enabled', False): raise ImproperlyConfigured('Error: trying to register {} as RPC method, but it has not been decorated.' .format(func.__name__)) # Define the external name of the function name = getattr(func, 'modernrpc_name', func.__name__) logger.debug('Register RPC method "{}"'.format(name)) if name.startswith('rpc.'): raise ImproperlyConfigured('According to RPC standard, method names starting with "rpc." are reserved for ' 'system extensions and must not be used. See ' 'http://www.jsonrpc.org/specification#extensions for more information.') # Encapsulate the function in a RPCMethod object method = RPCMethod(func) # Ensure method names are unique in the registry existing_method = self.get_method(method.name, ALL, ALL) if existing_method is not None: # Trying to register many times the same function is OK, because if a method is decorated # with @rpc_method(), it could be imported in different places of the code if method == existing_method: return method.name # But if we try to use the same name to register 2 different methods, we # must inform the developer there is an error in the code else: raise ImproperlyConfigured("A RPC method with name {} has already been registered".format(method.name)) # Store the method self._registry[method.name] = method logger.debug('Method registered. len(registry): {}'.format(len(self._registry))) return method.name
Register a function to be available as RPC method. The given function will be inspected to find external_name, protocol and entry_point values set by the decorator @rpc_method. :param func: A function previously decorated using @rpc_method :return: The name of registered method
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L249-L291
alorence/django-modern-rpc
modernrpc/core.py
_RPCRegistry.get_all_method_names
def get_all_method_names(self, entry_point=ALL, protocol=ALL, sort_methods=False): """Return the names of all RPC methods registered supported by the given entry_point / protocol pair""" method_names = [ name for name, method in self._registry.items() if method.is_valid_for(entry_point, protocol) ] if sort_methods: method_names = sorted(method_names) return method_names
python
def get_all_method_names(self, entry_point=ALL, protocol=ALL, sort_methods=False): """Return the names of all RPC methods registered supported by the given entry_point / protocol pair""" method_names = [ name for name, method in self._registry.items() if method.is_valid_for(entry_point, protocol) ] if sort_methods: method_names = sorted(method_names) return method_names
Return the names of all RPC methods registered supported by the given entry_point / protocol pair
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L296-L306
alorence/django-modern-rpc
modernrpc/core.py
_RPCRegistry.get_all_methods
def get_all_methods(self, entry_point=ALL, protocol=ALL, sort_methods=False): """Return a list of all methods in the registry supported by the given entry_point / protocol pair""" if sort_methods: return [ method for (_, method) in sorted(self._registry.items()) if method.is_valid_for(entry_point, protocol) ] return self._registry.values()
python
def get_all_methods(self, entry_point=ALL, protocol=ALL, sort_methods=False): """Return a list of all methods in the registry supported by the given entry_point / protocol pair""" if sort_methods: return [ method for (_, method) in sorted(self._registry.items()) if method.is_valid_for(entry_point, protocol) ] return self._registry.values()
Return a list of all methods in the registry supported by the given entry_point / protocol pair
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L308-L316
alorence/django-modern-rpc
modernrpc/core.py
_RPCRegistry.get_method
def get_method(self, name, entry_point, protocol): """Retrieve a method from the given name""" if name in self._registry and self._registry[name].is_valid_for(entry_point, protocol): return self._registry[name] return None
python
def get_method(self, name, entry_point, protocol): """Retrieve a method from the given name""" if name in self._registry and self._registry[name].is_valid_for(entry_point, protocol): return self._registry[name] return None
Retrieve a method from the given name
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L318-L324
alorence/django-modern-rpc
modernrpc/utils.py
logger_has_handlers
def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c = logger rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv
python
def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c = logger rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv
Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself.
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/utils.py#L17-L36
alorence/django-modern-rpc
modernrpc/utils.py
get_modernrpc_logger
def get_modernrpc_logger(name): """Get a logger from default logging manager. If no handler is associated, add a default NullHandler""" logger = logging.getLogger(name) if not logger_has_handlers(logger): # If logging is not configured in the current project, configure this logger to discard all logs messages. # This will prevent the 'No handlers could be found for logger XXX' error on Python 2, # and avoid redirecting errors to the default 'lastResort' StreamHandler on Python 3 logger.addHandler(logging.NullHandler()) return logger
python
def get_modernrpc_logger(name): """Get a logger from default logging manager. If no handler is associated, add a default NullHandler""" logger = logging.getLogger(name) if not logger_has_handlers(logger): # If logging is not configured in the current project, configure this logger to discard all logs messages. # This will prevent the 'No handlers could be found for logger XXX' error on Python 2, # and avoid redirecting errors to the default 'lastResort' StreamHandler on Python 3 logger.addHandler(logging.NullHandler()) return logger
Get a logger from default logging manager. If no handler is associated, add a default NullHandler
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/utils.py#L39-L47