idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
239,800
def wait_pid ( pid , timeout = None , callback = None ) : def check_timeout ( delay ) : if timeout is not None : if time . time ( ) >= stop_at : if callback : callback ( pid ) else : raise TimeoutExpired time . sleep ( delay ) return min ( delay * 2 , 0.04 ) if timeout is not None : waitcall = lambda : os . waitpid ( p...
Wait for process with pid pid to terminate and return its exit status code as an integer .
239,801
def get_filename ( self , filename , filesystem = False , convert = False , subpath = '' ) : from uliweb . utils . common import safe_unicode s = settings . GLOBAL if convert : _p , _f = os . path . split ( filename ) _filename = os . path . join ( _p , self . filename_convert ( _f ) ) else : _filename = filename nfile...
Get the filename according to self . to_path and if filesystem is False then return unicode filename otherwise return filesystem encoded filename
239,802
def download ( self , filename , action = 'download' , x_filename = '' , x_sendfile = None , real_filename = '' ) : from uliweb import request from uliweb . utils . common import safe_str from uliweb . utils . filedown import filedown s = settings . GLOBAL action = request . GET . get ( 'action' , action ) if not real_...
action will be download inline and if the request . GET has action then the action will be replaced by it .
239,803
def logout ( ) : from uliweb import request delete_user_session ( ) request . session . delete ( ) request . user = None return True
Remove the authenticated user s ID from the request .
239,804
def get ( self , key ) : if isinstance ( key , unicode ) : key = key . encode ( 'utf-8' ) v = self . client . get ( key ) if v is None : raise KeyError ( "Cache key [%s] not found" % key ) else : return v
because memcached does not provide a function to check if a key is existed so here is a heck way if the value is None then raise Exception
239,805
def get_commands ( mod ) : import inspect import types commands = { } def check ( c ) : return ( inspect . isclass ( c ) and issubclass ( c , Command ) and c is not Command and not issubclass ( c , CommandManager ) ) for name in dir ( mod ) : c = getattr ( mod , name ) if check ( c ) : commands [ c . name ] = c return ...
Find commands from a module
239,806
def usage ( self , subcommand ) : if len ( self . option_list ) > 0 : usage = '%%prog %s [options] %s' % ( subcommand , self . args ) else : usage = '%%prog %s %s' % ( subcommand , self . args ) if self . help : return '%s\n\n%s' % ( usage , self . help ) else : return usage
Return a brief description of how to use this command by default from the attribute self . help .
239,807
def show_table ( name , table , i , total ) : return '[%d/%d, %s] %s' % ( i + 1 , total , table . __appname__ , name )
Display table info name is tablename table is table object i is current Index total is total of tables
239,808
def get_template ( self , name ) : filename = path . join ( self . search_path , * [ p for p in name . split ( '/' ) if p and p [ 0 ] != '.' ] ) if not path . exists ( filename ) : raise TemplateNotFound ( name ) return Template . from_file ( filename , self . encoding )
Get a template from a given name .
239,809
def render_to_string ( self , * args , ** kwargs ) : try : template_name , args = args [ 0 ] , args [ 1 : ] except IndexError : raise TypeError ( 'name of template required' ) return self . get_template ( template_name ) . render ( * args , ** kwargs )
Load and render a template into a unicode string .
239,810
def get_template ( self , template_name ) : try : return self . loader . load ( template_name , encoding = self . encoding ) except self . not_found_exception , e : raise TemplateNotFound ( template_name )
Get the template which is at the given name
239,811
def render_to_string ( self , template_name , context = None ) : context = context or { } tmpl = self . get_template ( template_name ) return tmpl . generate ( ** context ) . render ( self . output_type , encoding = None )
Load and render a template into an unicode string
239,812
def process_permission_roles ( perm , v ) : if isinstance ( v , ( tuple , list ) ) : roles = v else : roles = [ v ] for r in roles : if isinstance ( r , ( tuple , list ) ) : role_name , role_props = r else : role_name , role_props = r , '' role = Role . get ( Role . c . name == role_name ) if not role : raise Exception...
v is roles
239,813
def generate_adapter ( adapter , name = 'url_for' , map_name = 'url_map' ) : values = { u'server_name' : dumps ( adapter . server_name ) , u'script_name' : dumps ( adapter . script_name ) , u'subdomain' : dumps ( adapter . subdomain ) , u'url_scheme' : dumps ( adapter . url_scheme ) , u'name' : name , u'map_name' : map...
Generates the url building function for a map .
239,814
def js_to_url_function ( converter ) : if hasattr ( converter , 'js_to_url_function' ) : data = converter . js_to_url_function ( ) else : for cls in getmro ( type ( converter ) ) : if cls in js_to_url_functions : data = js_to_url_functions [ cls ] ( converter ) break else : return 'encodeURIComponent' return '(function...
Get the JavaScript converter function from a rule .
239,815
def _warn_if_string ( iterable ) : if isinstance ( iterable , string_types ) : from warnings import warn warn ( Warning ( 'response iterable was set to a string. This appears ' 'to work but means that the server will send the ' 'data to the client char, by char. This is almost ' 'never intended behavior, use response...
Helper for the response objects to check if the iterable returned to the WSGI server is not a string .
239,816
def _get_file_stream ( self , total_content_length , content_type , filename = None , content_length = None ) : return default_stream_factory ( total_content_length , content_type , filename , content_length )
Called to get a stream for the file upload .
239,817
def close ( self ) : files = self . __dict__ . get ( 'files' ) for key , value in iter_multi_items ( files or ( ) ) : value . close ( )
Closes associated resources of this request object . This closes all file handles explicitly . You can also use the request object in a with statement with will automatically close it .
239,818
def get_data ( self , as_text = False ) : self . _ensure_sequence ( ) rv = b'' . join ( self . iter_encoded ( ) ) if as_text : rv = rv . decode ( self . charset ) return rv
The string representation of the request body . Whenever you call this property the request iterable is encoded and flattened . This can lead to unwanted behavior if you stream big data .
239,819
def _ensure_sequence ( self , mutable = False ) : if self . is_sequence : if mutable and not isinstance ( self . response , list ) : self . response = list ( self . response ) return if self . direct_passthrough : raise RuntimeError ( 'Attempted implicit sequence conversion ' 'but the response object is in direct ' 'pa...
This method can be called by methods that need a sequence . If mutable is true it will also ensure that the response sequence is a standard Python list .
239,820
def delete_cookie ( self , key , path = '/' , domain = None ) : self . set_cookie ( key , expires = 0 , max_age = 0 , path = path , domain = domain )
Delete a cookie . Fails silently if key doesn t exist .
239,821
def freeze ( self ) : self . response = list ( self . iter_encoded ( ) ) self . headers [ 'Content-Length' ] = str ( sum ( map ( len , self . response ) ) )
Call this method if you want to make your response object ready for being pickled . This buffers the generator if there is one . It will also set the Content - Length header to the length of the body .
239,822
def get_app_iter ( self , environ ) : status = self . status_code if environ [ 'REQUEST_METHOD' ] == 'HEAD' or 100 <= status < 200 or status in ( 204 , 304 ) : iterable = ( ) elif self . direct_passthrough : if __debug__ : _warn_if_string ( self . response ) return self . response else : iterable = self . iter_encoded ...
Returns the application iterator for the given environ . Depending on the request method and the current status code the return value might be an empty response rather than the one from the response .
239,823
def www_authenticate ( self ) : def on_update ( www_auth ) : if not www_auth and 'www-authenticate' in self . headers : del self . headers [ 'www-authenticate' ] elif www_auth : self . headers [ 'WWW-Authenticate' ] = www_auth . to_header ( ) header = self . headers . get ( 'www-authenticate' ) return parse_www_authent...
The WWW - Authenticate header in a parsed form .
239,824
def make_alias_redirect_url ( self , path , endpoint , values , method , query_args ) : url = self . build ( endpoint , values , method , append_unknown = False , force_external = True ) if query_args : url += '?' + self . encode_query_args ( query_args ) assert url != path , 'detected invalid alias setting. No canoni...
Internally called to make an alias redirect URL .
239,825
def from_file ( cls , file , charset = 'utf-8' , errors = 'strict' , unicode_mode = True ) : close = False f = file if isinstance ( file , basestring ) : f = open ( file , 'r' ) close = True try : data = _decode_unicode ( f . read ( ) , charset , errors ) finally : if close : f . close ( ) return cls ( data , getattr (...
Load a template from a file .
239,826
def safe_str_cmp ( a , b ) : if _builtin_safe_str_cmp is not None : return _builtin_safe_str_cmp ( a , b ) if len ( a ) != len ( b ) : return False rv = 0 if isinstance ( a , bytes ) and isinstance ( b , bytes ) and not PY2 : for x , y in izip ( a , b ) : rv |= x ^ y else : for x , y in izip ( a , b ) : rv |= ord ( x )...
This function compares strings in somewhat constant time . This requires that the length of at least one string is known in advance .
239,827
def gen_salt ( length ) : if length <= 0 : raise ValueError ( 'requested salt of length <= 0' ) return '' . join ( _sys_rng . choice ( SALT_CHARS ) for _ in range_type ( length ) )
Generate a random string of SALT_CHARS with specified length .
239,828
def html ( self , data = '' , py = True ) : if py : value = self . to_html ( data ) else : value = data if self . static : return str ( '<span class="value">%s</span>' % safe_str ( value ) ) else : if self . hidden : build = Hidden else : build = self . build self . _get_http_attrs ( ) return str ( build ( name = self ...
Convert data to html value format .
239,829
def validate ( self , data , all_data = None ) : all_data = all_data or { } if hasattr ( data , 'stream' ) : data . file = data . stream if hasattr ( data , 'file' ) : if data . file : v = data . filename else : raise Exception , 'Unsupport type %s' % type ( data ) else : v = data msg = TEST_NOT_EMPTY ( ) ( v ) if self...
if rule in kwargs then validate extra rules
239,830
def cache_property ( key , empty , type ) : return property ( lambda x : x . _get_cache_value ( key , empty , type ) , lambda x , v : x . _set_cache_value ( key , v , type ) , lambda x : x . _del_cache_value ( key ) , 'accessor for %r' % key )
Return a new property object for a cache header . Useful if you want to add support for a cache extension in a subclass .
239,831
def set ( self , start , stop , length = None , units = 'bytes' ) : assert is_byte_range_valid ( start , stop , length ) , 'Bad range provided' self . _units = units self . _start = start self . _stop = stop self . _length = length if self . on_update is not None : self . on_update ( self )
Simple method to update the ranges .
239,832
def qop ( self ) : def on_update ( header_set ) : if not header_set and 'qop' in self : del self [ 'qop' ] elif header_set : self [ 'qop' ] = header_set . to_header ( ) return parse_set_header ( self . get ( 'qop' ) , on_update )
Indicates what quality of protection the client has applied to the message for HTTP digest auth .
239,833
def set_basic ( self , realm = 'authentication required' ) : dict . clear ( self ) dict . update ( self , { '__auth_type__' : 'basic' , 'realm' : realm } ) if self . on_update : self . on_update ( self )
Clear the auth info and enable basic auth .
239,834
def get_connection ( connection = '' , engine_name = None , connection_type = 'long' , ** args ) : engine_name = engine_name or __default_engine__ if '://' in connection : d = { 'connection_string' : connection , 'connection_args' : args , 'connection_type' : connection_type , } return engine_manager . add ( engine_nam...
Creating an NamedEngine or just return existed engine instance
239,835
def get_metadata ( engine_name = None ) : dispatch . get ( None , 'load_models' ) engine = engine_manager [ engine_name ] for tablename , m in engine . models . items ( ) : get_model ( tablename , engine_name , signal = False ) if hasattr ( m , '__dynamic__' ) and getattr ( m , '__dynamic__' ) : m . table . __mapping_o...
get metadata according used for alembic It ll import all tables
239,836
def get_session ( ec = None , create = True ) : ec = ec or __default_engine__ if isinstance ( ec , ( str , unicode ) ) : session = engine_manager [ ec ] . session ( create = True ) elif isinstance ( ec , Session ) : session = ec else : raise Error ( "Connection %r should be existed engine name or Session object" % ec )...
ec - engine_name or connection
239,837
def rawsql ( query , ec = None ) : if isinstance ( query , Result ) : query = query . get_query ( ) ec = ec or __default_engine__ if isinstance ( ec , ( str , unicode ) ) : engine = engine_manager [ ec ] dialect = engine . engine . dialect else : dialect = ec . dialect if isinstance ( query , ( str , unicode ) ) : retu...
ec could be engine name or engine instance
239,838
def get_engine_name ( ec = None ) : ec = ec or __default_engine__ if isinstance ( ec , ( str , unicode ) ) : return ec elif isinstance ( ec , Session ) : return ec . engine_name else : raise Error ( "Parameter ec should be an engine_name or Session object, but %r found" % ec )
Get the name of a engine or session
239,839
def CommitAll ( close = None ) : if close : warnings . simplefilter ( 'default' ) warnings . warn ( "close parameter will not need at all." , DeprecationWarning ) for k , v in engine_manager . items ( ) : session = v . session ( create = False ) if session : session . commit ( )
Commit all transactions according Local . conn
239,840
def RollbackAll ( close = None ) : if close : warnings . simplefilter ( 'default' ) warnings . warn ( "close parameter will not need at all." , DeprecationWarning ) for k , v in engine_manager . items ( ) : session = v . session ( create = False ) if session : session . rollback ( )
Rollback all transactions according Local . conn
239,841
def set_model ( model , tablename = None , created = None , appname = None , model_path = None ) : if isinstance ( model , type ) and issubclass ( model , Model ) : tablename = model . _alias or model . tablename tablename = tablename . lower ( ) d = __models__ . setdefault ( tablename , { } ) engines = d . get ( 'conf...
Register an model and tablename to a global variable . model could be a string format i . e . uliweb . contrib . auth . models . User
239,842
def create_model ( modelname , fields , indexes = None , basemodel = None , ** props ) : assert not props or isinstance ( props , dict ) assert not indexes or isinstance ( indexes , list ) props = SortedDict ( props or { } ) props [ '__dynamic__' ] = True props [ '__config__' ] = False for p in fields : kwargs = p . co...
Create model dynamically
239,843
def reflect_table_model ( table , mapping = None , without_id = False , engine_name = 'default' ) : table = reflect_table ( table , engine_name ) mapping = mapping or { } meta = reflect_table_data ( table ) code = [ 'class {}(Model):' . format ( table . name . title ( ) ) ] code . append ( ' . format ( table . name ) )...
Write table to Model class
239,844
def SelfReferenceProperty ( label = None , collection_name = None , ** attrs ) : if 'reference_class' in attrs : raise ConfigurationError ( 'Do not provide reference_class to self-reference.' ) return ReferenceProperty ( _SELF_REFERENCE , label , collection_name , ** attrs )
Create a self reference .
239,845
def session ( self , create = True ) : if hasattr ( self . local , 'session' ) : return self . local . session else : if create : s = Session ( self . name ) self . local . session = s return s
Used to created default session
239,846
def get_parameters ( self ) : d = { } for k in [ 'label' , 'verbose_name' , 'required' , 'hint' , 'placeholder' , 'choices' , 'default' , 'validators' , 'max_length' ] : d [ k ] = getattr ( self , k ) return d
Get common attributes and it ll used for Model . relationship clone process
239,847
def validate ( self , value ) : if value == '' : if self . kwargs . get ( 'nullable' , __nullable__ ) : value = None else : value = 0 if not isinstance ( value , Model ) : return super ( ReferenceProperty , self ) . validate ( value ) if not value . is_saved ( ) : raise BadValueError ( '%s instance must be saved before...
Validate reference .
239,848
def get_fields ( self ) : columns = self . columns model = self . model fields = [ ] for col in columns : if isinstance ( col , ( str , unicode ) ) : v = col . split ( '.' ) if len ( v ) > 1 : field = get_model ( v [ 0 ] , engine_name = self . model . get_engine_name ( ) , signal = False ) . properties ( v [ 1 ] ) else...
get property instance according self . columns
239,849
def count ( self ) : if self . _group_by or self . _join or self . distinct_field : return self . do_ ( self . get_query ( ) . limit ( None ) . order_by ( None ) . offset ( None ) . alias ( ) . count ( ) ) . scalar ( ) else : return self . do_ ( self . get_query ( ) . with_only_columns ( [ func . count ( ) ] ) . limit ...
If result is True then the count will process result set if result if False then only use condition to count
239,850
def update ( self , ** kwargs ) : if self . condition is not None : self . result = self . do_ ( self . model . table . update ( ) . where ( self . condition ) . values ( ** kwargs ) ) else : self . result = self . do_ ( self . model . table . update ( ) . values ( ** kwargs ) ) return self . result
Execute update table set field = field + 1 like statement
239,851
def save_file ( self , filename , encoding = 'utf8' , headers = None , convertors = None , display = True , ** kwargs ) : global save_file convertors = convertors or { } headers = headers or [ ] fields = self . get_fields ( ) _header = [ ] for i , column in enumerate ( fields ) : if column . name not in convertors : if...
save result to a csv file . display = True will convert value according choices value
239,852
def all ( self , cache = False ) : if cache : return [ get_object ( self . modelb , obj_id , cache = True , use_local = True ) for obj_id in self . keys ( True ) ] else : return self
can use cache to return objects
239,853
def update ( self , * objs ) : keys = self . keys ( ) new_keys = get_objs_columns ( objs , self . realfieldb ) modified = False for v in new_keys : if v in keys : keys . remove ( v ) else : d = { self . fielda : self . valuea , self . fieldb : v } if self . before_save : self . before_save ( d ) if self . through_model...
Update the third relationship table but not the ModelA or ModelB
239,854
def with_relation ( self , relation_name = None ) : if not relation_name : relation_name = 'relation' if hasattr ( self . modelb , relation_name ) : raise Error ( "The attribute name %s has already existed in Model %s!" % ( relation_name , self . modelb . __name__ ) ) if not self . through_model : raise Error ( "Only w...
if relation is not None when fetch manytomany result also fetch relation record and saved them to manytomany object and named them as relation . If relation_name is not given then default value is relation
239,855
def in_ ( self , * objs ) : if not objs : return self . table . c [ self . fielda ] != self . table . c [ self . fielda ] else : keys = get_objs_columns ( objs , self . reference_fieldname ) sub_query = select ( [ self . table . c [ self . fielda ] ] , ( self . table . c [ self . fieldb ] == self . reference_class . c ...
Create a condition
239,856
def join_in ( self , * objs ) : if not objs : return self . table . c [ self . fielda ] != self . table . c [ self . fielda ] else : keys = get_objs_columns ( objs , self . reference_fieldname ) return ( self . table . c [ self . fielda ] == self . model_class . c [ self . reversed_fieldname ] ) & ( self . table . c [ ...
Create a join condition connect A and C
239,857
def join_right_in ( self , * objs ) : if not objs : return self . table . c [ self . fielda ] != self . table . c [ self . fielda ] else : keys = get_objs_columns ( objs , self . reference_fieldname ) return ( self . table . c [ self . fieldb ] == self . reference_class . c [ self . reference_fieldname ] ) & ( self . t...
Create a join condition connect B and C
239,858
def _get_data ( self , fields = None , compare = True ) : fields = fields or [ ] if self . _key is None or self . _key == '' or self . _key == 0 : d = { } for k , v in self . properties . items ( ) : if fields and k not in fields : continue if v . property_type == 'compound' : continue if v . sequence : continue if not...
Get the changed property it ll be used to save the object If compare is False then it ll include all data not only changed property
239,859
def create_sql ( self , insert = False , version = False , version_fieldname = None , fields = None , ec = None , compare = False ) : version_fieldname = version_fieldname or 'version' if not self . _key or insert : d = self . _get_data ( fields , compare = compare ) if d : return rawsql ( self . table . insert ( ) . v...
Create sql statement do not process manytomany
239,860
def get_collection_name ( cls , from_class_name , collection_name = None , prefix = None ) : if not collection_name : collection_name = prefix + '_set' if hasattr ( cls , collection_name ) : collection_name = prefix + '_set_' + str ( cls . _collection_set_id ) cls . _collection_set_id += 1 else : if collection_name in ...
Get reference collection_name if the collection_name is None then make sure the collection_name is not conflict but if the collection_name is not None then check if the collection_name is already exists if existed then raise Exception .
239,861
def _use ( cls , ec ) : ConnectModel = type ( cls . __name__ , ( cls , ) , { } ) ConnectModel . tablename = cls . tablename ConnectModel . _base_class = cls if isinstance ( ec , ( str , unicode ) ) : ConnectModel . _engine_name = ec elif isinstance ( ec , Session ) : ConnectModel . _engine_name = ec . engine_name Conne...
underly implement of use
239,862
def use ( cls , ec ) : if isinstance ( ec , ( str , unicode ) ) : m = get_model ( cls . _alias , ec , signal = False ) else : m = cls . _use ( ec ) return m
use will duplicate a new Model class and bind ec ec is Engine name or Sesstion object
239,863
def get_tree ( cls , * condition , ** kwargs ) : parent_field = kwargs . pop ( 'parent_field' , 'parent' ) parent = kwargs . pop ( 'parent' , None ) parent_order_by = kwargs . pop ( 'parent_order_by' , None ) current = kwargs . pop ( 'current' , None ) order_by = kwargs . pop ( 'order_by' , None ) id_field = kwargs . p...
parent is root parent value default is None current is current value condition is extra condition for select root records mode is search method value is wide or deep
239,864
def refresh ( self , fields = None , ** kwargs ) : cond = self . c [ self . _primary_field ] == self . _key query = self . filter ( cond , ** kwargs ) if not fields : fields = list ( self . table . c ) v = query . values_one ( * fields ) if not v : raise NotFound ( 'Instance <{0}:{1}> can not be found' . format ( self ...
Re get the instance of current id
239,865
def dump ( self , fields = None , exclude = None ) : exclude = exclude or [ ] d = { } if fields and self . _primary_field not in fields : fields = list ( fields ) fields . append ( self . _primary_field ) for k , v in self . properties . items ( ) : if ( ( not fields ) or ( k in fields ) ) and ( not exclude or ( k not ...
Dump current object to dict but the value is string for manytomany fields will not automatically be dumpped only when they are given in fields parameter
239,866
def clear_relation ( cls ) : for k , v in cls . properties . items ( ) : if isinstance ( v , ReferenceProperty ) : if hasattr ( v , 'collection_name' ) and hasattr ( v . reference_class , v . collection_name ) : delattr ( v . reference_class , v . collection_name ) if isinstance ( v , OneToOne ) : del v . reference_cla...
Clear relation properties for reference Model such as OneToOne Reference ManyToMany
239,867
def put ( self , _name , ** values ) : try : sql = self . sqles [ _name ] data = sql [ 'data' ] if sql [ 'positional' ] : d = [ values [ k ] for k , v in sql [ 'fields' ] . items ( ) ] else : d = { v : values [ k ] for k , v in sql [ 'fields' ] . items ( ) } data . append ( d ) if self . size and len ( data ) >= self ....
Put data to cach if reached size value it ll execute at once .
239,868
def get_key ( keyfile = None ) : keyfile = keyfile or application_path ( settings . SECRETKEY . SECRET_FILE ) with file ( keyfile , 'rb' ) as f : return f . read ( )
Read the key content from secret_file
239,869
def get_cipher_key ( keyfile = None ) : _key = get_key ( keyfile ) _k = md5 ( _key ) . hexdigest ( ) key = xor ( _k [ : 8 ] , _k [ 8 : 16 ] , _k [ 16 : 24 ] , _k [ 24 : ] ) return key
Create key which will be used in des because des need 8bytes chars
239,870
def set_many ( self , mapping , timeout = None ) : for key , value in _items ( mapping ) : self . set ( key , value , timeout )
Sets multiple keys and values from a mapping .
239,871
def dec ( self , key , delta = 1 ) : self . set ( key , ( self . get ( key ) or 0 ) - delta )
Decrements the value of a key by delta . If the key does not yet exist it is initialized with - delta .
239,872
def import_preferred_memcache_lib ( self , servers ) : try : import pylibmc except ImportError : pass else : return pylibmc . Client ( servers ) try : from google . appengine . api import memcache except ImportError : pass else : return memcache . Client ( ) try : import memcache except ImportError : pass else : return...
Returns an initialized memcache client . Used by the constructor .
239,873
def dump_object ( self , value ) : t = type ( value ) if t is int or t is long : return str ( value ) return '!' + pickle . dumps ( value )
Dumps an object into a string for redis . By default it serializes integers as regular string and pickle dumps everything else .
239,874
def extract_dirs ( mod , path , dst , verbose = False , exclude = None , exclude_ext = None , recursion = True , replace = True ) : default_exclude = [ '.svn' , '_svn' , '.git' ] default_exclude_ext = [ '.pyc' , '.pyo' , '.bak' , '.tmp' ] exclude = exclude or [ ] exclude_ext = exclude_ext or [ ] if not os . path . exis...
mod name path mod path dst output directory resursion True will extract all sub module of mod
239,875
def walk_dirs ( path , include = None , include_ext = None , exclude = None , exclude_ext = None , recursion = True , file_only = False , use_default_pattern = True , patterns = None ) : default_exclude = [ '.svn' , '_svn' , '.git' ] default_exclude_ext = [ '.pyc' , '.pyo' , '.bak' , '.tmp' ] exclude = exclude or [ ] e...
path directory path resursion True will extract all sub module of mod
239,876
def camel_to_ ( s ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , s ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
Convert CamelCase to camel_case
239,877
def application_path ( path ) : from uliweb import application return os . path . join ( application . project_dir , path )
Join application project_dir and path
239,878
def get_uuid ( type = 4 ) : import uuid name = 'uuid' + str ( type ) u = getattr ( uuid , name ) return u ( ) . hex
Get uuid value
239,879
def request_url ( req = None ) : from uliweb import request r = req or request if request : if r . query_string : return r . path + '?' + r . query_string else : return r . path else : return ''
Get full url of a request
239,880
def compare_dict ( da , db ) : sa = set ( da . items ( ) ) sb = set ( db . items ( ) ) diff = sa & sb return dict ( sa - diff ) , dict ( sb - diff )
Compare differencs from two dicts
239,881
def get_configrable_object ( key , section , cls = None ) : from uliweb import UliwebError , settings import inspect if inspect . isclass ( key ) and cls and issubclass ( key , cls ) : return key elif isinstance ( key , ( str , unicode ) ) : path = settings [ section ] . get ( key ) if path : _cls = import_attr ( path ...
if obj is a class then check if the class is subclass of cls or it should be object path and it ll be imported by import_attr
239,882
def convert_bytes ( n ) : symbols = ( 'K' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' , 'Y' ) prefix = { } for i , s in enumerate ( symbols ) : prefix [ s ] = 1 << ( i + 1 ) * 10 for s in reversed ( symbols ) : if n >= prefix [ s ] : value = float ( n ) / prefix [ s ] return '%.1f%s' % ( value , s ) return "%sB" % n
Convert a size number to K M . etc
239,883
def init_static_combine ( ) : from uliweb import settings from hashlib import md5 import os d = { } if settings . get_var ( 'STATIC_COMBINE_CONFIG/enable' , False ) : for k , v in settings . get ( 'STATIC_COMBINE' , { } ) . items ( ) : key = '_cmb_' + md5 ( '' . join ( v ) ) . hexdigest ( ) + os . path . splitext ( v [...
Process static combine create md5 key according each static filename
239,884
def csrf_token ( ) : from uliweb import request , settings from uliweb . utils . common import safe_str v = { } token_name = settings . CSRF . cookie_token_name if not request . session . deleted and request . session . get ( token_name ) : v = request . session [ token_name ] if time . time ( ) >= v [ 'created_time' ]...
Get csrf token or create new one
239,885
def json ( self ) : if 'json' not in self . environ . get ( 'CONTENT_TYPE' , '' ) : raise BadRequest ( 'Not a JSON request' ) try : return loads ( self . data ) except Exception : raise BadRequest ( 'Unable to read JSON request' )
Get the result of simplejson . loads if possible .
239,886
def parse_protobuf ( self , proto_type ) : if 'protobuf' not in self . environ . get ( 'CONTENT_TYPE' , '' ) : raise BadRequest ( 'Not a Protobuf request' ) obj = proto_type ( ) try : obj . ParseFromString ( self . data ) except Exception : raise BadRequest ( "Unable to parse Protobuf request" ) if self . protobuf_chec...
Parse the data into an instance of proto_type .
239,887
def charset ( self ) : header = self . environ . get ( 'CONTENT_TYPE' ) if header : ct , options = parse_options_header ( header ) charset = options . get ( 'charset' ) if charset : if is_known_charset ( charset ) : return charset return self . unknown_charset ( charset ) return self . default_charset
The charset from the content type .
239,888
def utf8 ( value ) : if isinstance ( value , _UTF8_TYPES ) : return value elif isinstance ( value , unicode_type ) : return value . encode ( "utf-8" ) else : return str ( value )
Converts a string argument to a byte string . If the argument is already a byte string or None it is returned unchanged . Otherwise it must be a unicode string and is encoded as utf8 .
239,889
def to_basestring ( value ) : if value is None : return 'None' if isinstance ( value , _BASESTRING_TYPES ) : return value elif isinstance ( value , unicode_type ) : return value . decode ( "utf-8" ) else : return str ( value )
Converts a string argument to a subclass of basestring . In python2 byte and unicode strings are mostly interchangeable so functions that deal with a user - supplied argument in combination with ascii string constants can use either and should return the type the user supplied . In python3 the two types are not interch...
239,890
def clear ( self ) : self . __values . clear ( ) self . __access_keys = [ ] self . __modified_times . clear ( )
Clears the dict .
239,891
def has ( self , key , mtime = None ) : v = self . __values . get ( key , None ) if not v : return False if self . check_modified_time : mtime = self . _get_mtime ( key , mtime ) if mtime != self . __modified_times [ key ] : del self [ key ] return False return True
This method should almost NEVER be used . The reason is that between the time has_key is called and the key is accessed the key might vanish .
239,892
def reset ( self ) : with self . lock : if self . cache : if self . use_tmp : shutil . rmtree ( self . tmp_dir , ignore_errors = True ) else : self . templates = { }
Resets the cache of compiled templates .
239,893
def has_role ( user , * roles , ** kwargs ) : Role = get_model ( 'role' ) if isinstance ( user , ( unicode , str ) ) : User = get_model ( 'user' ) user = User . get ( User . c . username == user ) for role in roles : if isinstance ( role , ( str , unicode ) ) : role = Role . get ( Role . c . name == role ) if not role ...
Judge is the user belongs to the role and if does then return the role object if not then return False . kwargs will be passed to role_func .
239,894
def has_permission ( user , * permissions , ** role_kwargs ) : Role = get_model ( 'role' ) Perm = get_model ( 'permission' ) if isinstance ( user , ( unicode , str ) ) : User = get_model ( 'user' ) user = User . get ( User . c . username == user ) for name in permissions : perm = Perm . get ( Perm . c . name == name ) ...
Judge if an user has permission and if it does return role object and if it doesn t return False . role_kwargs will be passed to role functions . With role object you can use role . relation to get Role_Perm_Rel object .
239,895
def load_ssl_context ( cert_file , pkey_file ) : from OpenSSL import SSL ctx = SSL . Context ( SSL . SSLv23_METHOD ) ctx . use_certificate_file ( cert_file ) ctx . use_privatekey_file ( pkey_file ) return ctx
Loads an SSL context from a certificate and private key file .
239,896
def select_ip_version ( host , port ) : if ':' in host and hasattr ( socket , 'AF_INET6' ) : return socket . AF_INET6 return socket . AF_INET
Returns AF_INET4 or AF_INET6 depending on where to connect to .
239,897
def make_server ( host , port , app = None , threaded = False , processes = 1 , request_handler = None , passthrough_errors = False , ssl_context = None ) : if threaded and processes > 1 : raise ValueError ( "cannot have a multithreaded and " "multi process server." ) elif threaded : return ThreadedWSGIServer ( host , ...
Create a new server instance that is either threaded or forks or just processes one request after another .
239,898
def _reloader_stat_loop ( extra_files = None , interval = 1 ) : from itertools import chain mtimes = { } while 1 : for filename in chain ( _iter_module_files ( ) , extra_files or ( ) ) : try : mtime = os . stat ( filename ) . st_mtime except OSError : continue old_time = mtimes . get ( filename ) if old_time is None : ...
When this function is run from the main thread it will force other threads to exit when any modules currently loaded change .
239,899
def run_simple ( hostname , port , application , use_reloader = False , use_debugger = False , use_evalex = True , extra_files = None , reloader_interval = 1 , threaded = False , processes = 1 , request_handler = None , static_files = None , passthrough_errors = False , ssl_context = None ) : if use_debugger : from wer...
Start an application using wsgiref and with an optional reloader . This wraps wsgiref to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support .