code
stringlengths 9
256k
|
---|
<s> """<STR_LIT>""" <EOL> from __future__ import with_statement <EOL> from google . appengine . tools import os_compat <EOL> import __builtin__ <EOL> import BaseHTTPServer <EOL> import base64 <EOL> import binascii <EOL> import calendar <EOL> import cStringIO <EOL> import cgi <EOL> import cgitb <EOL> import email . Utils <EOL> import errno <EOL> import hashlib <EOL> import heapq <EOL> import httplib <EOL> import imp <EOL> import inspect <EOL> import logging <EOL> import mimetools <EOL> import mimetypes <EOL> import os <EOL> import random <EOL> import select <EOL> import shutil <EOL> import simplejson <EOL> import struct <EOL> import tempfile <EOL> import yaml <EOL> import resource <EOL> import re <EOL> import sre_compile <EOL> import sre_constants <EOL> import sre_parse <EOL> import socket <EOL> import sys <EOL> import time <EOL> import types <EOL> import urlparse <EOL> import urllib <EOL> import zlib <EOL> import google <EOL> from google . appengine . api import apiproxy_stub_map <EOL> from google . appengine . api import appinfo <EOL> from google . appengine . api import appinfo_includes <EOL> from google . appengine . api import app_logging <EOL> from google . appengine . api import blobstore <EOL> from google . appengine . api import croninfo <EOL> from google . appengine . api import datastore <EOL> from google . appengine . api import lib_config <EOL> from google . appengine . api import mail <EOL> from google . appengine . api import namespace_manager <EOL> from google . appengine . api import urlfetch_stub <EOL> from google . appengine . api import user_service_stub <EOL> from google . appengine . api import yaml_errors <EOL> from google . appengine . api . app_identity import app_identity_stub <EOL> from google . appengine . api . capabilities import capability_stub <EOL> from google . appengine . api . channel import channel_service_stub <EOL> from google . appengine . api . files import file_service_stub <EOL> from google . appengine . api . logservice import logservice <EOL> from google . appengine . api . logservice import logservice_stub <EOL> from google . appengine . api . search import simple_search_stub <EOL> from google . appengine . api . prospective_search import prospective_search_stub <EOL> from google . appengine . api . remote_socket import _remote_socket_stub <EOL> from google . appengine . api import rdbms_mysqldb <EOL> from google . appengine . api . system import system_stub <EOL> from google . appengine . datastore import datastore_stub_util <EOL> from google . appengine . ext . cloudstorage import stub_dispatcher as gcs_dispatcher <EOL> from google . appengine import dist <EOL> from google . appengine . api . taskqueue import taskqueue_distributed <EOL> from google . appengine . api import mail_stub <EOL> from google . appengine . api . blobstore import blobstore_stub <EOL> from google . appengine . api import datastore_distributed <EOL> from google . appengine . api . blobstore import datastore_blob_storage <EOL> from google . appengine . api . memcache import memcache_distributed <EOL> from google . appengine . api . xmpp import xmpp_service_real <EOL> try : <EOL> from google . appengine . runtime import request_environment <EOL> from google . appengine . runtime import runtime <EOL> except : <EOL> request_environment = None <EOL> runtime = None <EOL> from google . appengine . tools import dev_appserver_apiserver <EOL> from google . appengine . tools import dev_appserver_blobimage <EOL> from google . appengine . tools import dev_appserver_blobstore <EOL> from google . appengine . tools import dev_appserver_channel <EOL> from google . appengine . tools import dev_appserver_import_hook <EOL> from google . appengine . tools import dev_appserver_login <EOL> from google . appengine . tools import dev_appserver_oauth <EOL> from google . storage . speckle . python . api import rdbms <EOL> CouldNotFindModuleError = dev_appserver_import_hook . CouldNotFindModuleError <EOL> FakeAccess = dev_appserver_import_hook . FakeAccess <EOL> FakeFile = dev_appserver_import_hook . FakeFile <EOL> FakeReadlink = dev_appserver_import_hook . FakeReadlink <EOL> FakeSetLocale = dev_appserver_import_hook . FakeSetLocale <EOL> FakeUnlink = dev_appserver_import_hook . FakeUnlink <EOL> GetSubmoduleName = dev_appserver_import_hook . GetSubmoduleName <EOL> HardenedModulesHook = dev_appserver_import_hook . HardenedModulesHook <EOL> SDK_ROOT = dev_appserver_import_hook . SDK_ROOT <EOL> PYTHON_LIB_VAR = '<STR_LIT>' <EOL> DEVEL_CONSOLE_PATH = PYTHON_LIB_VAR + '<STR_LIT>' <EOL> REMOTE_API_PATH = ( PYTHON_LIB_VAR + <EOL> '<STR_LIT>' ) <EOL> FILE_MISSING_EXCEPTIONS = frozenset ( [ errno . ENOENT , errno . ENOTDIR ] ) <EOL> MAX_URL_LENGTH = <NUM_LIT> <EOL> DEFAULT_ENV = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT:0>' , <EOL> } <EOL> DEFAULT_SELECT_DELAY = <NUM_LIT> <EOL> for ext , mime_type in mail . EXTENSION_MIME_MAP . iteritems ( ) : <EOL> mimetypes . add_type ( mime_type , '<STR_LIT:.>' + ext ) <EOL> MAX_RUNTIME_RESPONSE_SIZE = <NUM_LIT:32> << <NUM_LIT:20> <EOL> MAX_REQUEST_SIZE = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> <EOL> COPY_BLOCK_SIZE = <NUM_LIT:1> << <NUM_LIT:20> <EOL> API_VERSION = '<STR_LIT:1>' <EOL> VERSION_FILE = '<STR_LIT>' <EOL> DEVEL_PAYLOAD_HEADER = '<STR_LIT>' <EOL> DEVEL_PAYLOAD_RAW_HEADER = '<STR_LIT>' <EOL> DEVEL_FAKE_IS_ADMIN_HEADER = '<STR_LIT>' <EOL> DEVEL_FAKE_IS_ADMIN_RAW_HEADER = '<STR_LIT>' <EOL> FILE_STUB_DEPRECATION_MESSAGE = ( <EOL> """<STR_LIT>""" ) <EOL> NON_PUBLIC_CACHE_CONTROLS = frozenset ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> DASHBOARD_HTTPS_PORT = '<STR_LIT>' <EOL> class Error ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class InvalidAppConfigError ( Error ) : <EOL> """<STR_LIT>""" <EOL> class AppConfigNotFoundError ( Error ) : <EOL> """<STR_LIT>""" <EOL> class CompileError ( Error ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , text ) : <EOL> self . text = text <EOL> class ExecuteError ( Error ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , text , log ) : <EOL> self . text = text <EOL> self . log = log <EOL> def MonkeyPatchPdb ( pdb ) : <EOL> """<STR_LIT>""" <EOL> def NewSetTrace ( ) : <EOL> """<STR_LIT>""" <EOL> p = pdb . Pdb ( stdin = sys . __stdin__ , stdout = sys . __stdout__ ) <EOL> p . set_trace ( sys . _getframe ( ) . f_back ) <EOL> pdb . set_trace = NewSetTrace <EOL> def MonkeyPatchThreadingLocal ( _threading_local ) : <EOL> """<STR_LIT>""" <EOL> @ staticmethod <EOL> def New ( cls , * args , ** kw ) : <EOL> self = object . __new__ ( cls ) <EOL> key = '<STR_LIT>' , '<STR_LIT>' + str ( id ( self ) ) <EOL> object . __setattr__ ( self , '<STR_LIT>' , key ) <EOL> object . __setattr__ ( self , '<STR_LIT>' , ( args , kw ) ) <EOL> object . __setattr__ ( self , '<STR_LIT>' , _threading_local . RLock ( ) ) <EOL> if ( args or kw ) and ( cls . __init__ is object . __init__ ) : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> dict = object . __getattribute__ ( self , '<STR_LIT>' ) <EOL> _threading_local . current_thread ( ) . __dict__ [ key ] = dict <EOL> return self <EOL> _threading_local . _localbase . __new__ = New <EOL> def SplitURL ( relative_url ) : <EOL> """<STR_LIT>""" <EOL> ( unused_scheme , unused_netloc , path , query , <EOL> unused_fragment ) = urlparse . urlsplit ( relative_url ) <EOL> return path , query <EOL> def GetFullURL ( server_name , server_port , relative_url ) : <EOL> """<STR_LIT>""" <EOL> if str ( server_port ) != '<STR_LIT>' : <EOL> netloc = '<STR_LIT>' % ( server_name , server_port ) <EOL> else : <EOL> netloc = server_name <EOL> return '<STR_LIT>' % ( netloc , relative_url ) <EOL> def CopyStreamPart ( source , destination , content_size ) : <EOL> """<STR_LIT>""" <EOL> bytes_copied = <NUM_LIT:0> <EOL> bytes_left = content_size <EOL> while bytes_left > <NUM_LIT:0> : <EOL> bytes = source . read ( min ( bytes_left , COPY_BLOCK_SIZE ) ) <EOL> bytes_read = len ( bytes ) <EOL> if bytes_read == <NUM_LIT:0> : <EOL> break <EOL> destination . write ( bytes ) <EOL> bytes_copied += bytes_read <EOL> bytes_left -= bytes_read <EOL> return bytes_copied <EOL> def AppIdWithDefaultPartition ( app_id , default_partition ) : <EOL> """<STR_LIT>""" <EOL> if not default_partition : <EOL> return app_id <EOL> if '<STR_LIT>' in app_id : <EOL> return app_id <EOL> return default_partition + '<STR_LIT>' + app_id <EOL> class AppServerRequest ( object ) : <EOL> """<STR_LIT>""" <EOL> ATTRIBUTES = [ '<STR_LIT>' , <EOL> '<STR_LIT:path>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> def __init__ ( self , <EOL> relative_url , <EOL> path , <EOL> headers , <EOL> infile , <EOL> secret_hash , <EOL> force_admin = False ) : <EOL> """<STR_LIT>""" <EOL> self . relative_url = relative_url <EOL> self . path = path <EOL> self . headers = headers <EOL> self . infile = infile <EOL> self . force_admin = force_admin <EOL> if DEVEL_PAYLOAD_RAW_HEADER in self . headers : <EOL> if self . headers [ DEVEL_PAYLOAD_RAW_HEADER ] == secret_hash : <EOL> self . force_admin = True <EOL> if ( DEVEL_FAKE_IS_ADMIN_RAW_HEADER in self . headers ) : <EOL> if self . headers [ DEVEL_FAKE_IS_ADMIN_RAW_HEADER ] == secret_hash : <EOL> self . force_admin = True <EOL> def __eq__ ( self , other ) : <EOL> """<STR_LIT>""" <EOL> if type ( self ) == type ( other ) : <EOL> for attribute in self . ATTRIBUTES : <EOL> if getattr ( self , attribute ) != getattr ( other , attribute ) : <EOL> return False <EOL> return True <EOL> def __repr__ ( self ) : <EOL> """<STR_LIT>""" <EOL> results = [ ] <EOL> for attribute in self . ATTRIBUTES : <EOL> results . append ( '<STR_LIT>' % ( attribute , getattr ( self , attribute ) ) ) <EOL> return '<STR_LIT>' % '<STR_LIT:U+0020>' . join ( results ) <EOL> class URLDispatcher ( object ) : <EOL> """<STR_LIT>""" <EOL> def Dispatch ( self , <EOL> request , <EOL> outfile , <EOL> base_env_dict = None ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError <EOL> def EndRedirect ( self , dispatched_output , original_output ) : <EOL> """<STR_LIT>""" <EOL> original_output . write ( dispatched_output . read ( ) ) <EOL> class URLMatcher ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _url_patterns = [ ] <EOL> def AddURL ( self , regex , dispatcher , path , requires_login , admin_only , <EOL> auth_fail_action ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( dispatcher , URLDispatcher ) : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> if regex . startswith ( '<STR_LIT>' ) or regex . endswith ( '<STR_LIT:$>' ) : <EOL> raise InvalidAppConfigError ( '<STR_LIT>' ) <EOL> adjusted_regex = '<STR_LIT>' % regex <EOL> try : <EOL> url_re = re . compile ( adjusted_regex ) <EOL> except re . error , e : <EOL> raise InvalidAppConfigError ( '<STR_LIT>' % e ) <EOL> match_tuple = ( url_re , dispatcher , path , requires_login , admin_only , <EOL> auth_fail_action ) <EOL> self . _url_patterns . append ( match_tuple ) <EOL> def Match ( self , <EOL> relative_url , <EOL> split_url = SplitURL ) : <EOL> """<STR_LIT>""" <EOL> adjusted_url , unused_query_string = split_url ( relative_url ) <EOL> for url_tuple in self . _url_patterns : <EOL> url_re , dispatcher , path , requires_login , admin_only , auth_fail_action = url_tuple <EOL> the_match = url_re . match ( adjusted_url ) <EOL> if the_match : <EOL> adjusted_path = the_match . expand ( path ) <EOL> return ( dispatcher , adjusted_path , requires_login , admin_only , <EOL> auth_fail_action ) <EOL> return None , None , None , None , None <EOL> def GetDispatchers ( self ) : <EOL> """<STR_LIT>""" <EOL> return set ( [ url_tuple [ <NUM_LIT:1> ] for url_tuple in self . _url_patterns ] ) <EOL> class MatcherDispatcher ( URLDispatcher ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , <EOL> config , <EOL> login_url , <EOL> module_manager , <EOL> url_matchers , <EOL> get_user_info = dev_appserver_login . GetUserInfo , <EOL> login_redirect = dev_appserver_login . LoginRedirect ) : <EOL> """<STR_LIT>""" <EOL> self . _config = config <EOL> self . _login_url = login_url <EOL> self . _module_manager = module_manager <EOL> self . _url_matchers = tuple ( url_matchers ) <EOL> self . _get_user_info = get_user_info <EOL> self . _login_redirect = login_redirect <EOL> def Dispatch ( self , <EOL> request , <EOL> outfile , <EOL> base_env_dict = None ) : <EOL> """<STR_LIT>""" <EOL> cookies = '<STR_LIT:U+002CU+0020>' . join ( request . headers . getheaders ( '<STR_LIT>' ) ) <EOL> email_addr , user_id , admin , valid_cookie = self . _get_user_info ( cookies ) <EOL> for matcher in self . _url_matchers : <EOL> dispatcher , matched_path , requires_login , admin_only , auth_fail_action = matcher . Match ( request . relative_url ) <EOL> if dispatcher is None : <EOL> continue <EOL> logging . debug ( '<STR_LIT>' , <EOL> request . relative_url , dispatcher , matched_path ) <EOL> if ( ( requires_login or admin_only ) and <EOL> not email_addr and <EOL> not request . force_admin ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> if auth_fail_action == appinfo . AUTH_FAIL_ACTION_REDIRECT : <EOL> self . _login_redirect ( self . _login_url , <EOL> base_env_dict [ '<STR_LIT>' ] , <EOL> base_env_dict [ '<STR_LIT>' ] , <EOL> request . relative_url , <EOL> outfile ) <EOL> elif auth_fail_action == appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED : <EOL> outfile . write ( '<STR_LIT>' <EOL> '<STR_LIT:\r\n>' <EOL> '<STR_LIT>' <EOL> % ( httplib . UNAUTHORIZED ) ) <EOL> elif admin_only and not admin and not request . force_admin : <EOL> outfile . write ( '<STR_LIT>' <EOL> '<STR_LIT:\r\n>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> % ( httplib . FORBIDDEN , email_addr ) ) <EOL> else : <EOL> request . path = matched_path <EOL> if ( not isinstance ( dispatcher , FileDispatcher ) and <EOL> self . _module_manager . AreModuleFilesModified ( ) ) : <EOL> self . _module_manager . ResetModules ( ) <EOL> forward_request = dispatcher . Dispatch ( request , <EOL> outfile , <EOL> base_env_dict = base_env_dict ) <EOL> while forward_request : <EOL> logging . info ( '<STR_LIT>' , <EOL> forward_request . relative_url ) <EOL> new_outfile = cStringIO . StringIO ( ) <EOL> self . Dispatch ( forward_request , <EOL> new_outfile , <EOL> dict ( base_env_dict ) ) <EOL> new_outfile . seek ( <NUM_LIT:0> ) <EOL> forward_request = dispatcher . EndRedirect ( new_outfile , outfile ) <EOL> return <EOL> outfile . write ( '<STR_LIT>' <EOL> '<STR_LIT:\r\n>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> % ( httplib . NOT_FOUND , request . relative_url ) ) <EOL> _IGNORE_REQUEST_HEADERS = frozenset ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] ) <EOL> _request_id = <NUM_LIT:0> <EOL> _request_time = <NUM_LIT:0> <EOL> def _generate_request_id_hash ( ) : <EOL> """<STR_LIT>""" <EOL> return hashlib . sha1 ( str ( _request_id ) ) . hexdigest ( ) [ : <NUM_LIT:8> ] . upper ( ) <EOL> def _GenerateRequestLogId ( ) : <EOL> """<STR_LIT>""" <EOL> sec = int ( _request_time ) <EOL> usec = int ( <NUM_LIT> * ( _request_time - sec ) ) <EOL> h = hashlib . sha1 ( str ( _request_id ) ) . digest ( ) [ : <NUM_LIT:4> ] <EOL> packed = struct . Struct ( '<STR_LIT>' ) . pack ( sec , usec ) <EOL> return binascii . b2a_hex ( packed + h ) <EOL> def GetGoogleSqlOAuth2RefreshToken ( oauth_file_path ) : <EOL> """<STR_LIT>""" <EOL> if not os . path . exists ( oauth_file_path ) : <EOL> return None <EOL> try : <EOL> with open ( oauth_file_path ) as oauth_file : <EOL> token = simplejson . load ( oauth_file ) <EOL> return token [ '<STR_LIT>' ] <EOL> except ( IOError , KeyError , simplejson . decoder . JSONDecodeError ) : <EOL> logging . exception ( <EOL> '<STR_LIT>' , oauth_file_path ) <EOL> return None <EOL> def SetupEnvironment ( cgi_path , <EOL> relative_url , <EOL> headers , <EOL> infile , <EOL> split_url = SplitURL , <EOL> get_user_info = dev_appserver_login . GetUserInfo ) : <EOL> """<STR_LIT>""" <EOL> env = DEFAULT_ENV . copy ( ) <EOL> script_name , query_string = split_url ( relative_url ) <EOL> env [ '<STR_LIT>' ] = script_name <EOL> env [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> env [ '<STR_LIT>' ] = query_string <EOL> env [ '<STR_LIT>' ] = urllib . unquote ( script_name ) <EOL> env [ '<STR_LIT>' ] = cgi_path <EOL> env [ '<STR_LIT>' ] = headers . getheader ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> env [ '<STR_LIT>' ] = headers . getheader ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> cookies = '<STR_LIT:U+002CU+0020>' . join ( headers . getheaders ( '<STR_LIT>' ) ) <EOL> email_addr , user_id , admin , valid_cookie = get_user_info ( cookies ) <EOL> if valid_cookie : <EOL> env [ '<STR_LIT>' ] = email_addr <EOL> env [ '<STR_LIT>' ] = user_id <EOL> env [ '<STR_LIT>' ] = user_id <EOL> else : <EOL> env [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> env [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> env [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> env [ '<STR_LIT>' ] = '<STR_LIT:0>' <EOL> if admin and valid_cookie : <EOL> env [ '<STR_LIT>' ] = '<STR_LIT:1>' <EOL> if env [ '<STR_LIT>' ] == '<STR_LIT:*>' : <EOL> auth_domain = '<STR_LIT>' <EOL> parts = email_addr . split ( '<STR_LIT:@>' ) <EOL> if len ( parts ) == <NUM_LIT:2> and parts [ <NUM_LIT:1> ] : <EOL> auth_domain = parts [ <NUM_LIT:1> ] <EOL> env [ '<STR_LIT>' ] = auth_domain <EOL> env [ '<STR_LIT>' ] = _GenerateRequestLogId ( ) <EOL> env [ '<STR_LIT>' ] = _generate_request_id_hash ( ) <EOL> for key in headers : <EOL> if key in _IGNORE_REQUEST_HEADERS : <EOL> continue <EOL> adjusted_name = key . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) . upper ( ) <EOL> env [ '<STR_LIT>' + adjusted_name ] = '<STR_LIT:U+002CU+0020>' . join ( headers . getheaders ( key ) ) <EOL> if DEVEL_PAYLOAD_HEADER in env : <EOL> del env [ DEVEL_PAYLOAD_HEADER ] <EOL> new_data = base64 . standard_b64decode ( infile . getvalue ( ) ) <EOL> infile . seek ( <NUM_LIT:0> ) <EOL> infile . truncate ( ) <EOL> infile . write ( new_data ) <EOL> infile . seek ( <NUM_LIT:0> ) <EOL> env [ '<STR_LIT>' ] = str ( len ( new_data ) ) <EOL> if DEVEL_FAKE_IS_ADMIN_HEADER in env : <EOL> del env [ DEVEL_FAKE_IS_ADMIN_HEADER ] <EOL> token = GetGoogleSqlOAuth2RefreshToken ( os . path . expanduser ( <EOL> rdbms . OAUTH_CREDENTIALS_PATH ) ) <EOL> if token : <EOL> env [ '<STR_LIT>' ] = token <EOL> return env <EOL> def NotImplementedFake ( * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( '<STR_LIT>' ) <EOL> class NotImplementedFakeClass ( object ) : <EOL> """<STR_LIT>""" <EOL> __init__ = NotImplementedFake <EOL> def IsEncodingsModule ( module_name ) : <EOL> """<STR_LIT>""" <EOL> if ( module_name in ( '<STR_LIT>' , '<STR_LIT>' ) or <EOL> module_name . startswith ( '<STR_LIT>' ) ) : <EOL> return True <EOL> return False <EOL> def ClearAllButEncodingsModules ( module_dict ) : <EOL> """<STR_LIT>""" <EOL> for module_name in module_dict . keys ( ) : <EOL> if not IsEncodingsModule ( module_name ) and module_name != '<STR_LIT>' : <EOL> del module_dict [ module_name ] <EOL> def ConnectAndDisconnectChildModules ( old_module_dict , new_module_dict ) : <EOL> """<STR_LIT>""" <EOL> old_keys = set ( old_module_dict . keys ( ) ) <EOL> new_keys = set ( new_module_dict . keys ( ) ) <EOL> for deleted_module_name in old_keys - new_keys : <EOL> if old_module_dict [ deleted_module_name ] is None : <EOL> continue <EOL> segments = deleted_module_name . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> if len ( segments ) == <NUM_LIT:2> : <EOL> parent_module = new_module_dict . get ( segments [ <NUM_LIT:0> ] ) <EOL> if parent_module and hasattr ( parent_module , segments [ <NUM_LIT:1> ] ) : <EOL> delattr ( parent_module , segments [ <NUM_LIT:1> ] ) <EOL> for added_module_name in new_keys - old_keys : <EOL> if new_module_dict [ added_module_name ] is None : <EOL> continue <EOL> segments = added_module_name . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> if len ( segments ) == <NUM_LIT:2> : <EOL> parent_module = old_module_dict . get ( segments [ <NUM_LIT:0> ] ) <EOL> child_module = new_module_dict [ added_module_name ] <EOL> if ( parent_module and <EOL> getattr ( parent_module , segments [ <NUM_LIT:1> ] , None ) is not child_module ) : <EOL> setattr ( parent_module , segments [ <NUM_LIT:1> ] , child_module ) <EOL> SHARED_MODULE_PREFIXES = set ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:email>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] ) <EOL> NOT_SHARED_MODULE_PREFIXES = set ( [ <EOL> '<STR_LIT>' , <EOL> ] ) <EOL> def ModuleNameHasPrefix ( module_name , prefix_set ) : <EOL> """<STR_LIT>""" <EOL> for prefix in prefix_set : <EOL> if prefix == module_name : <EOL> return True <EOL> if module_name . startswith ( prefix + '<STR_LIT:.>' ) : <EOL> return True <EOL> return False <EOL> def SetupSharedModules ( module_dict ) : <EOL> """<STR_LIT>""" <EOL> output_dict = { } <EOL> for module_name , module in module_dict . iteritems ( ) : <EOL> if module is None : <EOL> continue <EOL> if IsEncodingsModule ( module_name ) : <EOL> output_dict [ module_name ] = module <EOL> continue <EOL> shared_prefix = ModuleNameHasPrefix ( module_name , SHARED_MODULE_PREFIXES ) <EOL> banned_prefix = ModuleNameHasPrefix ( module_name , NOT_SHARED_MODULE_PREFIXES ) <EOL> if shared_prefix and not banned_prefix : <EOL> output_dict [ module_name ] = module <EOL> return output_dict <EOL> def ModuleHasValidMainFunction ( module ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( module , '<STR_LIT>' ) and type ( module . main ) is types . FunctionType : <EOL> arg_names , var_args , var_kwargs , default_values = inspect . getargspec ( <EOL> module . main ) <EOL> if len ( arg_names ) == <NUM_LIT:0> : <EOL> return True <EOL> if default_values is not None and len ( arg_names ) == len ( default_values ) : <EOL> return True <EOL> return False <EOL> def CheckScriptExists ( cgi_path , handler_path ) : <EOL> """<STR_LIT>""" <EOL> if handler_path . startswith ( PYTHON_LIB_VAR + '<STR_LIT:/>' ) : <EOL> return <EOL> if ( not os . path . isdir ( cgi_path ) and <EOL> not os . path . isfile ( cgi_path ) and <EOL> os . path . isfile ( cgi_path + '<STR_LIT>' ) ) : <EOL> raise CouldNotFindModuleError ( <EOL> '<STR_LIT>' % <EOL> handler_path ) <EOL> def GetScriptModuleName ( handler_path ) : <EOL> """<STR_LIT>""" <EOL> if handler_path . startswith ( PYTHON_LIB_VAR + '<STR_LIT:/>' ) : <EOL> handler_path = handler_path [ len ( PYTHON_LIB_VAR ) : ] <EOL> handler_path = os . path . normpath ( handler_path ) <EOL> extension_index = handler_path . rfind ( '<STR_LIT>' ) <EOL> if extension_index != - <NUM_LIT:1> : <EOL> handler_path = handler_path [ : extension_index ] <EOL> module_fullname = handler_path . replace ( os . sep , '<STR_LIT:.>' ) <EOL> module_fullname = module_fullname . strip ( '<STR_LIT:.>' ) <EOL> module_fullname = re . sub ( '<STR_LIT>' , '<STR_LIT:.>' , module_fullname ) <EOL> if module_fullname . endswith ( '<STR_LIT>' ) : <EOL> module_fullname = module_fullname [ : - len ( '<STR_LIT>' ) ] <EOL> return module_fullname <EOL> def FindMissingInitFiles ( cgi_path , module_fullname , isfile = os . path . isfile ) : <EOL> """<STR_LIT>""" <EOL> missing_init_files = [ ] <EOL> if cgi_path . endswith ( '<STR_LIT>' ) : <EOL> module_base = os . path . dirname ( cgi_path ) <EOL> else : <EOL> module_base = cgi_path <EOL> depth_count = module_fullname . count ( '<STR_LIT:.>' ) <EOL> if cgi_path . endswith ( '<STR_LIT>' ) or not cgi_path . endswith ( '<STR_LIT>' ) : <EOL> depth_count += <NUM_LIT:1> <EOL> for index in xrange ( depth_count ) : <EOL> current_init_file = os . path . abspath ( <EOL> os . path . join ( module_base , '<STR_LIT>' ) ) <EOL> if not isfile ( current_init_file ) : <EOL> missing_init_files . append ( current_init_file ) <EOL> module_base = os . path . abspath ( os . path . join ( module_base , os . pardir ) ) <EOL> return missing_init_files <EOL> def LoadTargetModule ( handler_path , <EOL> cgi_path , <EOL> import_hook , <EOL> module_dict = sys . modules ) : <EOL> """<STR_LIT>""" <EOL> CheckScriptExists ( cgi_path , handler_path ) <EOL> module_fullname = GetScriptModuleName ( handler_path ) <EOL> script_module = module_dict . get ( module_fullname ) <EOL> module_code = None <EOL> if script_module is not None and ModuleHasValidMainFunction ( script_module ) : <EOL> logging . debug ( '<STR_LIT>' , module_fullname ) <EOL> else : <EOL> if script_module is None : <EOL> script_module = imp . new_module ( module_fullname ) <EOL> script_module . __loader__ = import_hook <EOL> try : <EOL> module_code = import_hook . get_code ( module_fullname ) <EOL> full_path , search_path , submodule = ( <EOL> import_hook . GetModuleInfo ( module_fullname ) ) <EOL> script_module . __file__ = full_path <EOL> if search_path is not None : <EOL> script_module . __path__ = search_path <EOL> except UnicodeDecodeError , e : <EOL> error = ( '<STR_LIT>' <EOL> '<STR_LIT>' % ( e , handler_path ) ) <EOL> raise SyntaxError ( error ) <EOL> except : <EOL> exc_type , exc_value , exc_tb = sys . exc_info ( ) <EOL> import_error_message = str ( exc_type ) <EOL> if exc_value : <EOL> import_error_message += '<STR_LIT>' + str ( exc_value ) <EOL> logging . exception ( '<STR_LIT>' , <EOL> module_fullname , import_error_message ) <EOL> missing_inits = FindMissingInitFiles ( cgi_path , module_fullname ) <EOL> if missing_inits : <EOL> logging . warning ( '<STR_LIT>' , <EOL> '<STR_LIT:U+002CU+0020>' . join ( missing_inits ) ) <EOL> else : <EOL> logging . error ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> independent_load_successful = True <EOL> if not os . path . isfile ( cgi_path ) : <EOL> independent_load_successful = False <EOL> else : <EOL> try : <EOL> source_file = open ( cgi_path ) <EOL> try : <EOL> module_code = compile ( source_file . read ( ) , cgi_path , '<STR_LIT>' ) <EOL> script_module . __file__ = cgi_path <EOL> finally : <EOL> source_file . close ( ) <EOL> except OSError : <EOL> independent_load_successful = False <EOL> if not independent_load_successful : <EOL> raise exc_type , exc_value , exc_tb <EOL> module_dict [ module_fullname ] = script_module <EOL> return module_fullname , script_module , module_code <EOL> def _WriteErrorToOutput ( status , message , outfile ) : <EOL> """<STR_LIT>""" <EOL> logging . error ( message ) <EOL> outfile . write ( '<STR_LIT>' % ( status , message ) ) <EOL> def GetRequestSize ( request , env_dict , outfile ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT>' in request . headers : <EOL> request_size = int ( request . headers [ '<STR_LIT>' ] ) <EOL> elif env_dict and env_dict . get ( '<STR_LIT>' , '<STR_LIT>' ) == '<STR_LIT:POST>' : <EOL> _WriteErrorToOutput ( '<STR_LIT>' % httplib . LENGTH_REQUIRED , <EOL> '<STR_LIT>' , <EOL> outfile ) <EOL> return None <EOL> else : <EOL> request_size = <NUM_LIT:0> <EOL> if request_size <= MAX_REQUEST_SIZE : <EOL> return request_size <EOL> else : <EOL> msg = ( '<STR_LIT>' <EOL> % ( request_size , MAX_REQUEST_SIZE ) ) <EOL> _WriteErrorToOutput ( <EOL> '<STR_LIT>' % httplib . REQUEST_ENTITY_TOO_LARGE , <EOL> msg , outfile ) <EOL> return None <EOL> def ExecuteOrImportScript ( config , handler_path , cgi_path , import_hook ) : <EOL> """<STR_LIT>""" <EOL> module_fullname , script_module , module_code = LoadTargetModule ( <EOL> handler_path , cgi_path , import_hook ) <EOL> script_module . __name__ = '<STR_LIT:__main__>' <EOL> sys . modules [ '<STR_LIT:__main__>' ] = script_module <EOL> try : <EOL> import pdb <EOL> MonkeyPatchPdb ( pdb ) <EOL> if module_code : <EOL> exec module_code in script_module . __dict__ <EOL> else : <EOL> script_module . main ( ) <EOL> sys . stdout . flush ( ) <EOL> sys . stdout . seek ( <NUM_LIT:0> ) <EOL> try : <EOL> headers = mimetools . Message ( sys . stdout ) <EOL> finally : <EOL> sys . stdout . seek ( <NUM_LIT:0> , <NUM_LIT:2> ) <EOL> status_header = headers . get ( '<STR_LIT:status>' ) <EOL> error_response = False <EOL> if status_header : <EOL> try : <EOL> status_code = int ( status_header . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) [ <NUM_LIT:0> ] ) <EOL> error_response = status_code >= <NUM_LIT> <EOL> except ValueError : <EOL> error_response = True <EOL> if not error_response : <EOL> try : <EOL> parent_package = import_hook . GetParentPackage ( module_fullname ) <EOL> except Exception : <EOL> parent_package = None <EOL> if parent_package is not None : <EOL> submodule = GetSubmoduleName ( module_fullname ) <EOL> setattr ( parent_package , submodule , script_module ) <EOL> return error_response <EOL> finally : <EOL> script_module . __name__ = module_fullname <EOL> def ExecutePy27Handler ( config , handler_path , cgi_path , import_hook ) : <EOL> """<STR_LIT>""" <EOL> if request_environment is None or runtime is None : <EOL> raise RuntimeError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> import os <EOL> save_environ = os . environ <EOL> save_getenv = os . getenv <EOL> env = dict ( save_environ ) <EOL> if env . get ( '<STR_LIT>' ) : <EOL> env [ '<STR_LIT>' ] = True <EOL> url = '<STR_LIT>' % ( env . get ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> env . get ( '<STR_LIT>' , '<STR_LIT:/>' ) ) <EOL> qs = env . get ( '<STR_LIT>' ) <EOL> if qs : <EOL> url += '<STR_LIT:?>' + qs <EOL> post_data = sys . stdin . read ( ) <EOL> if '<STR_LIT>' in env : <EOL> if post_data : <EOL> env [ '<STR_LIT>' ] = env [ '<STR_LIT>' ] <EOL> del env [ '<STR_LIT>' ] <EOL> if '<STR_LIT>' in env : <EOL> if env [ '<STR_LIT>' ] : <EOL> env [ '<STR_LIT>' ] = env [ '<STR_LIT>' ] <EOL> del env [ '<STR_LIT>' ] <EOL> if cgi_path . endswith ( handler_path ) : <EOL> application_root = cgi_path [ : - len ( handler_path ) ] <EOL> if application_root . endswith ( '<STR_LIT:/>' ) and application_root != '<STR_LIT:/>' : <EOL> application_root = application_root [ : - <NUM_LIT:1> ] <EOL> else : <EOL> application_root = '<STR_LIT>' <EOL> try : <EOL> import pdb <EOL> MonkeyPatchPdb ( pdb ) <EOL> import _threading_local <EOL> MonkeyPatchThreadingLocal ( _threading_local ) <EOL> os . environ = request_environment . RequestLocalEnviron ( <EOL> request_environment . current_request ) <EOL> os . getenv = os . environ . get <EOL> response = runtime . HandleRequest ( env , handler_path , url , <EOL> post_data , application_root , SDK_ROOT , <EOL> import_hook ) <EOL> finally : <EOL> os . environ = save_environ <EOL> os . getenv = save_getenv <EOL> error = response . get ( '<STR_LIT:error>' ) <EOL> if error : <EOL> status = <NUM_LIT> <EOL> else : <EOL> status = <NUM_LIT:200> <EOL> status = response . get ( '<STR_LIT>' , status ) <EOL> sys . stdout . write ( '<STR_LIT>' % status ) <EOL> for key , value in response . get ( '<STR_LIT>' , ( ) ) : <EOL> key = '<STR_LIT:->' . join ( key . split ( ) ) <EOL> value = value . replace ( '<STR_LIT:\r>' , '<STR_LIT:U+0020>' ) . replace ( '<STR_LIT:\n>' , '<STR_LIT:U+0020>' ) <EOL> sys . stdout . write ( '<STR_LIT>' % ( key , value ) ) <EOL> sys . stdout . write ( '<STR_LIT:\r\n>' ) <EOL> body = response . get ( '<STR_LIT:body>' ) <EOL> if body : <EOL> sys . stdout . write ( body ) <EOL> logs = response . get ( '<STR_LIT>' ) <EOL> if logs : <EOL> for timestamp_usec , severity , message in logs : <EOL> logging . log ( severity * <NUM_LIT:10> + <NUM_LIT:10> , '<STR_LIT>' , <EOL> time . ctime ( timestamp_usec * <NUM_LIT> ) , message ) <EOL> return error <EOL> class LoggingStream ( object ) : <EOL> """<STR_LIT>""" <EOL> def write ( self , message ) : <EOL> logging . getLogger ( ) . _log ( logging . ERROR , message , ( ) ) <EOL> def writelines ( self , lines ) : <EOL> for line in lines : <EOL> logging . getLogger ( ) . _log ( logging . ERROR , line , ( ) ) <EOL> def __getattr__ ( self , key ) : <EOL> return getattr ( sys . __stderr__ , key ) <EOL> def ExecuteCGI ( config , <EOL> root_path , <EOL> handler_path , <EOL> cgi_path , <EOL> env , <EOL> infile , <EOL> outfile , <EOL> module_dict , <EOL> exec_script = ExecuteOrImportScript , <EOL> exec_py27_handler = ExecutePy27Handler ) : <EOL> """<STR_LIT>""" <EOL> if handler_path == '<STR_LIT>' : <EOL> from google . appengine . ext . go import execute_go_cgi <EOL> return execute_go_cgi ( root_path , handler_path , cgi_path , <EOL> env , infile , outfile ) <EOL> old_module_dict = sys . modules . copy ( ) <EOL> old_builtin = __builtin__ . __dict__ . copy ( ) <EOL> old_argv = sys . argv <EOL> old_stdin = sys . stdin <EOL> old_stdout = sys . stdout <EOL> old_stderr = sys . stderr <EOL> old_env = os . environ . copy ( ) <EOL> old_cwd = os . getcwd ( ) <EOL> old_file_type = types . FileType <EOL> reset_modules = False <EOL> app_log_handler = None <EOL> try : <EOL> ConnectAndDisconnectChildModules ( sys . modules , module_dict ) <EOL> ClearAllButEncodingsModules ( sys . modules ) <EOL> sys . modules . update ( module_dict ) <EOL> sys . argv = [ cgi_path ] <EOL> sys . stdin = cStringIO . StringIO ( infile . getvalue ( ) ) <EOL> sys . stdout = outfile <EOL> sys . stderr = LoggingStream ( ) <EOL> logservice . _global_buffer = logservice . LogsBuffer ( ) <EOL> app_log_handler = app_logging . AppLogsHandler ( ) <EOL> logging . getLogger ( ) . addHandler ( app_log_handler ) <EOL> os . environ . clear ( ) <EOL> os . environ . update ( env ) <EOL> cgi_dir = os . path . normpath ( os . path . dirname ( cgi_path ) ) <EOL> root_path = os . path . normpath ( os . path . abspath ( root_path ) ) <EOL> if ( cgi_dir . startswith ( root_path + os . sep ) and <EOL> not ( config and config . runtime == '<STR_LIT>' ) ) : <EOL> os . chdir ( cgi_dir ) <EOL> else : <EOL> os . chdir ( root_path ) <EOL> dist . fix_paths ( root_path , SDK_ROOT ) <EOL> hook = HardenedModulesHook ( config , sys . modules , root_path ) <EOL> sys . meta_path = [ finder for finder in sys . meta_path <EOL> if not isinstance ( finder , HardenedModulesHook ) ] <EOL> sys . meta_path . insert ( <NUM_LIT:0> , hook ) <EOL> if hasattr ( sys , '<STR_LIT>' ) : <EOL> sys . path_importer_cache . clear ( ) <EOL> __builtin__ . file = FakeFile <EOL> __builtin__ . open = FakeFile <EOL> types . FileType = FakeFile <EOL> if not ( config and config . runtime == '<STR_LIT>' ) : <EOL> __builtin__ . buffer = NotImplementedFakeClass <EOL> sys . modules [ '<STR_LIT>' ] = __builtin__ <EOL> logging . debug ( '<STR_LIT>' , repr ( env ) ) <EOL> try : <EOL> if handler_path and config and config . runtime == '<STR_LIT>' : <EOL> reset_modules = exec_py27_handler ( config , handler_path , cgi_path , hook ) <EOL> else : <EOL> reset_modules = exec_script ( config , handler_path , cgi_path , hook ) <EOL> except SystemExit , e : <EOL> logging . debug ( '<STR_LIT>' , e ) <EOL> except : <EOL> reset_modules = True <EOL> raise <EOL> finally : <EOL> sys . path_importer_cache . clear ( ) <EOL> _ClearTemplateCache ( sys . modules ) <EOL> module_dict . update ( sys . modules ) <EOL> ConnectAndDisconnectChildModules ( sys . modules , old_module_dict ) <EOL> ClearAllButEncodingsModules ( sys . modules ) <EOL> sys . modules . update ( old_module_dict ) <EOL> __builtin__ . __dict__ . update ( old_builtin ) <EOL> sys . argv = old_argv <EOL> sys . stdin = old_stdin <EOL> sys . stdout = old_stdout <EOL> sys . stderr = old_stderr <EOL> logging . getLogger ( ) . removeHandler ( app_log_handler ) <EOL> os . environ . clear ( ) <EOL> os . environ . update ( old_env ) <EOL> os . chdir ( old_cwd ) <EOL> types . FileType = old_file_type <EOL> class CGIDispatcher ( URLDispatcher ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , <EOL> config , <EOL> module_dict , <EOL> root_path , <EOL> path_adjuster , <EOL> setup_env = SetupEnvironment , <EOL> exec_cgi = ExecuteCGI ) : <EOL> """<STR_LIT>""" <EOL> self . _config = config <EOL> self . _module_dict = module_dict <EOL> self . _root_path = root_path <EOL> self . _path_adjuster = path_adjuster <EOL> self . _setup_env = setup_env <EOL> self . _exec_cgi = exec_cgi <EOL> def Dispatch ( self , <EOL> request , <EOL> outfile , <EOL> base_env_dict = None ) : <EOL> """<STR_LIT>""" <EOL> request_size = GetRequestSize ( request , base_env_dict , outfile ) <EOL> if request_size is None : <EOL> return <EOL> memory_file = cStringIO . StringIO ( ) <EOL> CopyStreamPart ( request . infile , memory_file , request_size ) <EOL> memory_file . seek ( <NUM_LIT:0> ) <EOL> before_level = logging . root . level <EOL> try : <EOL> env = { } <EOL> if self . _config . env_variables : <EOL> env . update ( self . _config . env_variables ) <EOL> if base_env_dict : <EOL> env . update ( base_env_dict ) <EOL> cgi_path = self . _path_adjuster . AdjustPath ( request . path ) <EOL> env . update ( self . _setup_env ( cgi_path , <EOL> request . relative_url , <EOL> request . headers , <EOL> memory_file ) ) <EOL> self . _exec_cgi ( self . _config , <EOL> self . _root_path , <EOL> request . path , <EOL> cgi_path , <EOL> env , <EOL> memory_file , <EOL> outfile , <EOL> self . _module_dict ) <EOL> finally : <EOL> logging . root . level = before_level <EOL> def __str__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' <EOL> class LocalCGIDispatcher ( CGIDispatcher ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , config , module_dict , path_adjuster , cgi_func ) : <EOL> """<STR_LIT>""" <EOL> self . _cgi_func = cgi_func <EOL> def curried_exec_script ( * args , ** kwargs ) : <EOL> cgi_func ( ) <EOL> return False <EOL> def curried_exec_cgi ( * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = curried_exec_script <EOL> return ExecuteCGI ( * args , ** kwargs ) <EOL> CGIDispatcher . __init__ ( self , <EOL> config , <EOL> module_dict , <EOL> '<STR_LIT>' , <EOL> path_adjuster , <EOL> exec_cgi = curried_exec_cgi ) <EOL> def Dispatch ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> self . _module_dict . update ( sys . modules ) <EOL> CGIDispatcher . Dispatch ( self , * args , ** kwargs ) <EOL> def __str__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' % self . _cgi_func <EOL> class PathAdjuster ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , root_path ) : <EOL> """<STR_LIT>""" <EOL> self . _root_path = os . path . abspath ( root_path ) <EOL> def AdjustPath ( self , path ) : <EOL> """<STR_LIT>""" <EOL> if path . startswith ( PYTHON_LIB_VAR ) : <EOL> path = os . path . join ( SDK_ROOT , path [ len ( PYTHON_LIB_VAR ) + <NUM_LIT:1> : ] ) <EOL> else : <EOL> path = os . path . join ( self . _root_path , path ) <EOL> return path <EOL> class StaticFileConfigMatcher ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , <EOL> url_map_list , <EOL> default_expiration ) : <EOL> """<STR_LIT>""" <EOL> if default_expiration is not None : <EOL> self . _default_expiration = appinfo . ParseExpiration ( default_expiration ) <EOL> else : <EOL> self . _default_expiration = None <EOL> self . _patterns = [ ] <EOL> for url_map in url_map_list or [ ] : <EOL> handler_type = url_map . GetHandlerType ( ) <EOL> if handler_type not in ( appinfo . STATIC_FILES , appinfo . STATIC_DIR ) : <EOL> continue <EOL> path_re = _StaticFilePathRe ( url_map ) <EOL> try : <EOL> self . _patterns . append ( ( re . compile ( path_re ) , url_map ) ) <EOL> except re . error , e : <EOL> raise InvalidAppConfigError ( '<STR_LIT>' % <EOL> ( path_re , e ) ) <EOL> _DUMMY_URLMAP = appinfo . URLMap ( ) <EOL> def _FirstMatch ( self , path ) : <EOL> """<STR_LIT>""" <EOL> for path_re , url_map in self . _patterns : <EOL> if path_re . match ( path ) : <EOL> return url_map <EOL> return StaticFileConfigMatcher . _DUMMY_URLMAP <EOL> def IsStaticFile ( self , path ) : <EOL> """<STR_LIT>""" <EOL> return self . _FirstMatch ( path ) is not self . _DUMMY_URLMAP <EOL> def GetMimeType ( self , path ) : <EOL> """<STR_LIT>""" <EOL> url_map = self . _FirstMatch ( path ) <EOL> if url_map . mime_type is not None : <EOL> return url_map . mime_type <EOL> unused_filename , extension = os . path . splitext ( path ) <EOL> return mimetypes . types_map . get ( extension , '<STR_LIT>' ) <EOL> def GetExpiration ( self , path ) : <EOL> """<STR_LIT>""" <EOL> if self . _default_expiration is None : <EOL> return <NUM_LIT:0> <EOL> url_map = self . _FirstMatch ( path ) <EOL> if url_map . expiration is None : <EOL> return self . _default_expiration <EOL> return appinfo . ParseExpiration ( url_map . expiration ) <EOL> def GetHttpHeaders ( self , path ) : <EOL> """<STR_LIT>""" <EOL> return self . _FirstMatch ( path ) . http_headers or appinfo . HttpHeadersDict ( ) <EOL> def ReadDataFile ( data_path , openfile = file ) : <EOL> """<STR_LIT>""" <EOL> status = httplib . INTERNAL_SERVER_ERROR <EOL> data = "<STR_LIT>" <EOL> try : <EOL> data_file = openfile ( data_path , '<STR_LIT:rb>' ) <EOL> try : <EOL> data = data_file . read ( ) <EOL> finally : <EOL> data_file . close ( ) <EOL> status = httplib . OK <EOL> except ( OSError , IOError ) , e : <EOL> logging . error ( '<STR_LIT>' , data_path , e ) <EOL> if e . errno in FILE_MISSING_EXCEPTIONS : <EOL> status = httplib . NOT_FOUND <EOL> else : <EOL> status = httplib . FORBIDDEN <EOL> return status , data <EOL> class FileDispatcher ( URLDispatcher ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , <EOL> config , <EOL> path_adjuster , <EOL> static_file_config_matcher , <EOL> read_data_file = ReadDataFile ) : <EOL> """<STR_LIT>""" <EOL> self . _config = config <EOL> self . _path_adjuster = path_adjuster <EOL> self . _static_file_config_matcher = static_file_config_matcher <EOL> self . _read_data_file = read_data_file <EOL> def Dispatch ( self , request , outfile , base_env_dict = None ) : <EOL> """<STR_LIT>""" <EOL> full_path = self . _path_adjuster . AdjustPath ( request . path ) <EOL> status , data = self . _read_data_file ( full_path ) <EOL> content_type = self . _static_file_config_matcher . GetMimeType ( request . path ) <EOL> static_file = self . _static_file_config_matcher . IsStaticFile ( request . path ) <EOL> expiration = self . _static_file_config_matcher . GetExpiration ( request . path ) <EOL> current_etag = self . CreateEtag ( data ) <EOL> if_match_etag = request . headers . get ( '<STR_LIT>' , None ) <EOL> if_none_match_etag = request . headers . get ( '<STR_LIT>' , '<STR_LIT>' ) . split ( '<STR_LIT:U+002C>' ) <EOL> http_headers = self . _static_file_config_matcher . GetHttpHeaders ( request . path ) <EOL> def WriteHeader ( name , value ) : <EOL> if http_headers . Get ( name ) is None : <EOL> outfile . write ( '<STR_LIT>' % ( name , value ) ) <EOL> if if_match_etag and not self . _CheckETagMatches ( if_match_etag . split ( '<STR_LIT:U+002C>' ) , <EOL> current_etag , <EOL> False ) : <EOL> outfile . write ( '<STR_LIT>' % httplib . PRECONDITION_FAILED ) <EOL> WriteHeader ( '<STR_LIT>' , current_etag ) <EOL> outfile . write ( '<STR_LIT:\r\n>' ) <EOL> elif self . _CheckETagMatches ( if_none_match_etag , current_etag , True ) : <EOL> outfile . write ( '<STR_LIT>' % httplib . NOT_MODIFIED ) <EOL> WriteHeader ( '<STR_LIT>' , current_etag ) <EOL> outfile . write ( '<STR_LIT:\r\n>' ) <EOL> else : <EOL> outfile . write ( '<STR_LIT>' % status ) <EOL> WriteHeader ( '<STR_LIT:Content-Type>' , content_type ) <EOL> if expiration : <EOL> fmt = email . Utils . formatdate <EOL> WriteHeader ( '<STR_LIT>' , fmt ( time . time ( ) + expiration , usegmt = True ) ) <EOL> WriteHeader ( '<STR_LIT>' , '<STR_LIT>' % expiration ) <EOL> if static_file : <EOL> WriteHeader ( '<STR_LIT>' , '<STR_LIT>' % current_etag ) <EOL> for header in http_headers . iteritems ( ) : <EOL> outfile . write ( '<STR_LIT>' % header ) <EOL> outfile . write ( '<STR_LIT:\r\n>' ) <EOL> outfile . write ( data ) <EOL> def __str__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' <EOL> @ staticmethod <EOL> def CreateEtag ( data ) : <EOL> """<STR_LIT>""" <EOL> data_crc = zlib . crc32 ( data ) <EOL> return base64 . b64encode ( str ( data_crc ) ) <EOL> @ staticmethod <EOL> def _CheckETagMatches ( supplied_etags , current_etag , allow_weak_match ) : <EOL> """<STR_LIT>""" <EOL> for tag in supplied_etags : <EOL> if allow_weak_match and tag . startswith ( '<STR_LIT>' ) : <EOL> tag = tag [ <NUM_LIT:2> : ] <EOL> tag_data = tag . strip ( '<STR_LIT:">' ) <EOL> if tag_data == '<STR_LIT:*>' or tag_data == current_etag : <EOL> return True <EOL> return False <EOL> _IGNORE_RESPONSE_HEADERS = frozenset ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:date>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> blobstore . BLOB_KEY_HEADER <EOL> ] ) <EOL> class AppServerResponse ( object ) : <EOL> """<STR_LIT>""" <EOL> __slots__ = [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:body>' , <EOL> '<STR_LIT>' ] <EOL> def __init__ ( self , response_file = None , ** kwds ) : <EOL> """<STR_LIT>""" <EOL> self . status_code = <NUM_LIT:200> <EOL> self . status_message = '<STR_LIT>' <EOL> self . large_response = False <EOL> if response_file : <EOL> self . SetResponse ( response_file ) <EOL> else : <EOL> self . headers = mimetools . Message ( cStringIO . StringIO ( ) ) <EOL> self . body = None <EOL> for name , value in kwds . iteritems ( ) : <EOL> setattr ( self , name , value ) <EOL> def SetResponse ( self , response_file ) : <EOL> """<STR_LIT>""" <EOL> self . headers = mimetools . Message ( response_file ) <EOL> self . body = response_file <EOL> @ property <EOL> def header_data ( self ) : <EOL> """<STR_LIT>""" <EOL> header_list = [ ] <EOL> for header in self . headers . headers : <EOL> header = header . rstrip ( '<STR_LIT>' ) <EOL> header_list . append ( header ) <EOL> if not self . headers . getheader ( '<STR_LIT:Content-Type>' ) : <EOL> header_list . append ( '<STR_LIT>' ) <EOL> return '<STR_LIT:\r\n>' . join ( header_list ) + '<STR_LIT:\r\n>' <EOL> def IgnoreHeadersRewriter ( response ) : <EOL> """<STR_LIT>""" <EOL> for h in _IGNORE_RESPONSE_HEADERS : <EOL> if h in response . headers : <EOL> del response . headers [ h ] <EOL> def ValidHeadersRewriter ( response ) : <EOL> """<STR_LIT>""" <EOL> for ( key , value ) in response . headers . items ( ) : <EOL> try : <EOL> key . decode ( '<STR_LIT:ascii>' ) <EOL> value . decode ( '<STR_LIT:ascii>' ) <EOL> except UnicodeDecodeError : <EOL> del response . headers [ key ] <EOL> def ParseStatusRewriter ( response ) : <EOL> """<STR_LIT>""" <EOL> location_value = response . headers . getheader ( '<STR_LIT:location>' ) <EOL> status_value = response . headers . getheader ( '<STR_LIT:status>' ) <EOL> if status_value : <EOL> response_status = status_value <EOL> del response . headers [ '<STR_LIT:status>' ] <EOL> elif location_value : <EOL> response_status = '<STR_LIT>' % httplib . FOUND <EOL> else : <EOL> return response <EOL> status_parts = response_status . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> response . status_code , response . status_message = ( status_parts + [ '<STR_LIT>' ] ) [ : <NUM_LIT:2> ] <EOL> try : <EOL> response . status_code = int ( response . status_code ) <EOL> except ValueError : <EOL> response . status_code = <NUM_LIT> <EOL> response . body = cStringIO . StringIO ( <EOL> '<STR_LIT>' ) <EOL> def GetAllHeaders ( message , name ) : <EOL> """<STR_LIT>""" <EOL> for header_line in message . getallmatchingheaders ( name ) : <EOL> yield header_line . split ( '<STR_LIT::>' , <NUM_LIT:1> ) [ <NUM_LIT:1> ] . strip ( ) <EOL> def CacheRewriter ( response ) : <EOL> """<STR_LIT>""" <EOL> if response . status_code == httplib . NOT_MODIFIED : <EOL> return <EOL> if not '<STR_LIT>' in response . headers : <EOL> response . headers [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> if not '<STR_LIT>' in response . headers : <EOL> response . headers [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> if '<STR_LIT>' in response . headers : <EOL> current_date = time . time ( ) <EOL> expires = response . headers . get ( '<STR_LIT>' ) <EOL> reset_expires = True <EOL> if expires : <EOL> expires_time = email . Utils . parsedate ( expires ) <EOL> if expires_time : <EOL> reset_expires = calendar . timegm ( expires_time ) >= current_date <EOL> if reset_expires : <EOL> response . headers [ '<STR_LIT>' ] = time . strftime ( '<STR_LIT>' , <EOL> time . gmtime ( current_date ) ) <EOL> cache_directives = [ ] <EOL> for header in GetAllHeaders ( response . headers , '<STR_LIT>' ) : <EOL> cache_directives . extend ( v . strip ( ) for v in header . split ( '<STR_LIT:U+002C>' ) ) <EOL> cache_directives = [ d for d in cache_directives if d != '<STR_LIT>' ] <EOL> if not NON_PUBLIC_CACHE_CONTROLS . intersection ( cache_directives ) : <EOL> cache_directives . append ( '<STR_LIT>' ) <EOL> response . headers [ '<STR_LIT>' ] = '<STR_LIT:U+002CU+0020>' . join ( cache_directives ) <EOL> def _RemainingDataSize ( input_buffer ) : <EOL> """<STR_LIT>""" <EOL> current_position = input_buffer . tell ( ) <EOL> input_buffer . seek ( <NUM_LIT:0> , <NUM_LIT:2> ) <EOL> remaining_data_size = input_buffer . tell ( ) - current_position <EOL> input_buffer . seek ( current_position ) <EOL> return remaining_data_size <EOL> def ContentLengthRewriter ( response , request_headers , env_dict ) : <EOL> """<STR_LIT>""" <EOL> if env_dict and env_dict . get ( '<STR_LIT>' , '<STR_LIT>' ) == '<STR_LIT>' : <EOL> return <EOL> if response . status_code != httplib . NOT_MODIFIED : <EOL> response . headers [ '<STR_LIT>' ] = str ( _RemainingDataSize ( response . body ) ) <EOL> elif '<STR_LIT>' in response . headers : <EOL> del response . headers [ '<STR_LIT>' ] <EOL> def CreateResponseRewritersChain ( ) : <EOL> """<STR_LIT>""" <EOL> rewriters = [ ParseStatusRewriter , <EOL> dev_appserver_blobstore . DownloadRewriter , <EOL> IgnoreHeadersRewriter , <EOL> ValidHeadersRewriter , <EOL> CacheRewriter , <EOL> ContentLengthRewriter , <EOL> ] <EOL> return rewriters <EOL> def RewriteResponse ( response_file , <EOL> response_rewriters = None , <EOL> request_headers = None , <EOL> env_dict = None ) : <EOL> """<STR_LIT>""" <EOL> if response_rewriters is None : <EOL> response_rewriters = CreateResponseRewritersChain ( ) <EOL> response = AppServerResponse ( response_file ) <EOL> for response_rewriter in response_rewriters : <EOL> if response_rewriter . func_code . co_argcount == <NUM_LIT:1> : <EOL> response_rewriter ( response ) <EOL> elif response_rewriter . func_code . co_argcount == <NUM_LIT:2> : <EOL> response_rewriter ( response , request_headers ) <EOL> else : <EOL> response_rewriter ( response , request_headers , env_dict ) <EOL> return response <EOL> class ModuleManager ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , modules ) : <EOL> """<STR_LIT>""" <EOL> self . _modules = modules <EOL> self . _default_modules = self . _modules . copy ( ) <EOL> self . _save_path_hooks = sys . path_hooks [ : ] <EOL> self . _modification_times = { } <EOL> self . _dirty = True <EOL> @ staticmethod <EOL> def GetModuleFile ( module , is_file = os . path . isfile ) : <EOL> """<STR_LIT>""" <EOL> module_file = getattr ( module , '<STR_LIT>' , None ) <EOL> if module_file is None : <EOL> return None <EOL> source_file = module_file [ : module_file . rfind ( '<STR_LIT>' ) + <NUM_LIT:2> ] <EOL> if is_file ( source_file ) : <EOL> return source_file <EOL> return module . __file__ <EOL> def AreModuleFilesModified ( self ) : <EOL> """<STR_LIT>""" <EOL> for name , ( mtime , fname ) in self . _modification_times . iteritems ( ) : <EOL> if name not in self . _modules : <EOL> continue <EOL> module = self . _modules [ name ] <EOL> try : <EOL> if mtime != os . path . getmtime ( fname ) : <EOL> self . _dirty = True <EOL> return True <EOL> except OSError , e : <EOL> if e . errno in FILE_MISSING_EXCEPTIONS : <EOL> self . _dirty = True <EOL> return True <EOL> raise e <EOL> return False <EOL> def UpdateModuleFileModificationTimes ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . _dirty : <EOL> return <EOL> self . _modification_times . clear ( ) <EOL> for name , module in self . _modules . items ( ) : <EOL> if not isinstance ( module , types . ModuleType ) : <EOL> continue <EOL> module_file = self . GetModuleFile ( module ) <EOL> if not module_file : <EOL> continue <EOL> try : <EOL> self . _modification_times [ name ] = ( os . path . getmtime ( module_file ) , <EOL> module_file ) <EOL> except OSError , e : <EOL> if e . errno not in FILE_MISSING_EXCEPTIONS : <EOL> raise e <EOL> self . _dirty = False <EOL> def ResetModules ( self ) : <EOL> """<STR_LIT>""" <EOL> lib_config . _default_registry . reset ( ) <EOL> self . _modules . clear ( ) <EOL> self . _modules . update ( self . _default_modules ) <EOL> sys . path_hooks [ : ] = self . _save_path_hooks <EOL> sys . meta_path = [ ] <EOL> apiproxy_stub_map . apiproxy . GetPreCallHooks ( ) . Clear ( ) <EOL> apiproxy_stub_map . apiproxy . GetPostCallHooks ( ) . Clear ( ) <EOL> def GetVersionObject ( isfile = os . path . isfile , open_fn = open ) : <EOL> """<STR_LIT>""" <EOL> version_filename = os . path . join ( os . path . dirname ( google . appengine . __file__ ) , <EOL> VERSION_FILE ) <EOL> if not isfile ( version_filename ) : <EOL> logging . error ( '<STR_LIT>' , version_filename ) <EOL> return None <EOL> version_fh = open_fn ( version_filename , '<STR_LIT:r>' ) <EOL> try : <EOL> version = yaml . safe_load ( version_fh ) <EOL> finally : <EOL> version_fh . close ( ) <EOL> return version <EOL> def _ClearTemplateCache ( module_dict = sys . modules ) : <EOL> """<STR_LIT>""" <EOL> template_module = module_dict . get ( '<STR_LIT>' ) <EOL> if template_module is not None : <EOL> template_module . template_cache . clear ( ) <EOL> def CreateRequestHandler ( root_path , <EOL> login_url , <EOL> static_caching = True , <EOL> default_partition = None , <EOL> interactive_console = True , <EOL> secret_hash = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> application_module_dict = SetupSharedModules ( sys . modules ) <EOL> application_config_cache = AppConfigCache ( ) <EOL> class DevAppServerRequestHandler ( BaseHTTPServer . BaseHTTPRequestHandler ) : <EOL> """<STR_LIT>""" <EOL> server_version = '<STR_LIT>' <EOL> module_dict = application_module_dict <EOL> module_manager = ModuleManager ( application_module_dict ) <EOL> config_cache = application_config_cache <EOL> rewriter_chain = CreateResponseRewritersChain ( ) <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> self . _log_record_writer = logservice_stub . RequestLogWriter ( ) <EOL> BaseHTTPServer . BaseHTTPRequestHandler . __init__ ( self , * args , ** kwargs ) <EOL> def version_string ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . server_version <EOL> def do_GET ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _HasNoBody ( '<STR_LIT:GET>' ) : <EOL> self . _HandleRequest ( ) <EOL> def do_POST ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _HandleRequest ( ) <EOL> def do_PUT ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _HandleRequest ( ) <EOL> def do_HEAD ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _HasNoBody ( '<STR_LIT>' ) : <EOL> self . _HandleRequest ( ) <EOL> def do_OPTIONS ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _HandleRequest ( ) <EOL> def do_DELETE ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _HandleRequest ( ) <EOL> def do_TRACE ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _HasNoBody ( '<STR_LIT>' ) : <EOL> self . _HandleRequest ( ) <EOL> def _HasNoBody ( self , method ) : <EOL> """<STR_LIT>""" <EOL> content_length = int ( self . headers . get ( '<STR_LIT>' , <NUM_LIT:0> ) ) <EOL> if content_length : <EOL> body = self . rfile . read ( content_length ) <EOL> logging . warning ( '<STR_LIT>' , method , body ) <EOL> self . send_response ( httplib . BAD_REQUEST ) <EOL> return False <EOL> return True <EOL> def _Dispatch ( self , dispatcher , socket_infile , outfile , env_dict ) : <EOL> """<STR_LIT>""" <EOL> request_descriptor , request_file_name = tempfile . mkstemp ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> try : <EOL> request_file = open ( request_file_name , '<STR_LIT:wb>' ) <EOL> try : <EOL> CopyStreamPart ( self . rfile , <EOL> request_file , <EOL> int ( self . headers . get ( '<STR_LIT>' , <NUM_LIT:0> ) ) ) <EOL> finally : <EOL> request_file . close ( ) <EOL> request_file = open ( request_file_name , '<STR_LIT:rb>' ) <EOL> try : <EOL> app_server_request = AppServerRequest ( self . path , <EOL> None , <EOL> self . headers , <EOL> request_file , <EOL> secret_hash ) <EOL> dispatcher . Dispatch ( app_server_request , <EOL> outfile , <EOL> base_env_dict = env_dict ) <EOL> finally : <EOL> request_file . close ( ) <EOL> finally : <EOL> try : <EOL> os . close ( request_descriptor ) <EOL> try : <EOL> os . remove ( request_file_name ) <EOL> except OSError , err : <EOL> if getattr ( err , '<STR_LIT>' , <NUM_LIT:0> ) == os_compat . ERROR_SHARING_VIOLATION : <EOL> logging . warning ( '<STR_LIT>' , request_file_name ) <EOL> else : <EOL> raise <EOL> except OSError , err : <EOL> if err . errno != errno . ENOENT : <EOL> raise <EOL> def _HandleRequest ( self ) : <EOL> """<STR_LIT>""" <EOL> host_name = self . headers . get ( '<STR_LIT:host>' ) or self . server . server_name <EOL> server_name = host_name . split ( '<STR_LIT::>' , <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> env_dict = { <EOL> '<STR_LIT>' : self . command , <EOL> '<STR_LIT>' : self . headers . get ( "<STR_LIT>" , self . client_address [ <NUM_LIT:0> ] ) , <EOL> '<STR_LIT>' : self . server_version , <EOL> '<STR_LIT>' : server_name , <EOL> '<STR_LIT>' : self . protocol_version , <EOL> '<STR_LIT>' : str ( self . server . server_port ) , <EOL> } <EOL> full_url = GetFullURL ( server_name , self . server . server_port , self . path ) <EOL> if len ( full_url ) > MAX_URL_LENGTH : <EOL> msg = '<STR_LIT>' % full_url <EOL> logging . error ( msg ) <EOL> self . send_response ( httplib . REQUEST_URI_TOO_LONG , msg ) <EOL> return <EOL> tbhandler = cgitb . Hook ( file = self . wfile ) . handle <EOL> try : <EOL> config , explicit_matcher , from_cache = LoadAppConfig ( <EOL> root_path , self . module_dict , cache = self . config_cache , <EOL> static_caching = static_caching , default_partition = default_partition ) <EOL> if not from_cache : <EOL> self . module_manager . ResetModules ( ) <EOL> implicit_matcher = CreateImplicitMatcher ( config , <EOL> self . module_dict , <EOL> root_path , <EOL> login_url ) <EOL> if self . path . startswith ( '<STR_LIT>' ) : <EOL> if any ( ( handler . url == '<STR_LIT>' <EOL> for handler in config . handlers ) ) : <EOL> self . headers [ '<STR_LIT>' ] = '<STR_LIT:True>' <EOL> self . headers [ '<STR_LIT>' ] = str ( <EOL> interactive_console ) <EOL> if config . api_version != API_VERSION : <EOL> logging . error ( <EOL> "<STR_LIT>" , <EOL> config . api_version , API_VERSION ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> ( exclude , service_match ) = ReservedPathFilter ( <EOL> config . inbound_services ) . ExcludePath ( self . path ) <EOL> if exclude : <EOL> logging . warning ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' % ( self . path , service_match ) ) <EOL> self . send_response ( httplib . NOT_FOUND ) <EOL> return <EOL> if config . runtime == '<STR_LIT>' : <EOL> from google . appengine . ext import go <EOL> go . APP_CONFIG = config <EOL> version = GetVersionObject ( ) <EOL> env_dict [ '<STR_LIT>' ] = version [ '<STR_LIT>' ] <EOL> env_dict [ '<STR_LIT>' ] = config . version + "<STR_LIT>" <EOL> env_dict [ '<STR_LIT>' ] = config . application <EOL> env_dict [ '<STR_LIT>' ] = self . server . frontend_hostport <EOL> env_dict [ '<STR_LIT>' ] = config . runtime <EOL> if config . runtime == '<STR_LIT>' and config . threadsafe : <EOL> env_dict [ '<STR_LIT>' ] = '<STR_LIT:1>' <EOL> global _request_time <EOL> global _request_id <EOL> _request_time = time . time ( ) <EOL> _request_id += <NUM_LIT:1> <EOL> request_id_hash = _generate_request_id_hash ( ) <EOL> env_dict [ '<STR_LIT>' ] = request_id_hash <EOL> os . environ [ '<STR_LIT>' ] = request_id_hash <EOL> cookies = '<STR_LIT:U+002CU+0020>' . join ( self . headers . getheaders ( '<STR_LIT>' ) ) <EOL> email_addr , user_id , admin , valid_cookie = dev_appserver_login . GetUserInfo ( cookies ) <EOL> self . _log_record_writer . write_request_info ( <EOL> ip = env_dict [ '<STR_LIT>' ] , <EOL> app_id = env_dict [ '<STR_LIT>' ] , <EOL> version_id = env_dict [ '<STR_LIT>' ] , <EOL> nickname = email_addr . split ( '<STR_LIT:@>' ) [ <NUM_LIT:0> ] , <EOL> user_agent = self . headers . get ( '<STR_LIT>' ) , <EOL> host = host_name ) <EOL> dispatcher = MatcherDispatcher ( config , login_url , self . module_manager , <EOL> [ implicit_matcher , explicit_matcher ] ) <EOL> outfile = cStringIO . StringIO ( ) <EOL> try : <EOL> self . _Dispatch ( dispatcher , self . rfile , outfile , env_dict ) <EOL> finally : <EOL> self . module_manager . UpdateModuleFileModificationTimes ( ) <EOL> outfile . flush ( ) <EOL> outfile . seek ( <NUM_LIT:0> ) <EOL> response = RewriteResponse ( outfile , self . rewriter_chain , self . headers , <EOL> env_dict ) <EOL> runtime_response_size = _RemainingDataSize ( response . body ) <EOL> if self . command == '<STR_LIT>' and runtime_response_size > <NUM_LIT:0> : <EOL> logging . warning ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> response . body = cStringIO . StringIO ( '<STR_LIT>' ) <EOL> elif ( not response . large_response and <EOL> runtime_response_size > MAX_RUNTIME_RESPONSE_SIZE ) : <EOL> logging . error ( '<STR_LIT>' , <EOL> runtime_response_size , MAX_RUNTIME_RESPONSE_SIZE ) <EOL> response . status_code = <NUM_LIT> <EOL> response . status_message = '<STR_LIT>' <EOL> new_response = ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> % ( runtime_response_size , <EOL> MAX_RUNTIME_RESPONSE_SIZE ) ) <EOL> response . headers [ '<STR_LIT>' ] = str ( len ( new_response ) ) <EOL> response . body = cStringIO . StringIO ( new_response ) <EOL> except yaml_errors . EventListenerError , e : <EOL> title = '<STR_LIT>' <EOL> msg = '<STR_LIT>' % ( title , str ( e ) ) <EOL> logging . error ( msg ) <EOL> self . send_response ( httplib . INTERNAL_SERVER_ERROR , title ) <EOL> self . wfile . write ( '<STR_LIT>' ) <EOL> self . wfile . write ( '<STR_LIT>' % cgi . escape ( msg ) ) <EOL> except KeyboardInterrupt , e : <EOL> logging . info ( '<STR_LIT>' ) <EOL> self . server . stop_serving_forever ( ) <EOL> except CompileError , e : <EOL> msg = '<STR_LIT>' + e . text + '<STR_LIT:\n>' <EOL> logging . error ( msg ) <EOL> self . send_response ( httplib . INTERNAL_SERVER_ERROR , '<STR_LIT>' ) <EOL> self . wfile . write ( '<STR_LIT>' ) <EOL> self . wfile . write ( msg ) <EOL> except ExecuteError , e : <EOL> logging . error ( e . text ) <EOL> self . send_response ( httplib . INTERNAL_SERVER_ERROR , '<STR_LIT>' ) <EOL> self . wfile . write ( '<STR_LIT>' ) <EOL> self . wfile . write ( '<STR_LIT>' ) <EOL> self . wfile . write ( e . text + '<STR_LIT>' ) <EOL> for l in e . log : <EOL> self . wfile . write ( cgi . escape ( l ) ) <EOL> self . wfile . write ( '<STR_LIT>' ) <EOL> except : <EOL> msg = '<STR_LIT>' <EOL> logging . exception ( msg ) <EOL> self . send_response ( httplib . INTERNAL_SERVER_ERROR , msg ) <EOL> tbhandler ( ) <EOL> else : <EOL> try : <EOL> self . send_response ( response . status_code , response . status_message ) <EOL> self . wfile . write ( response . header_data ) <EOL> self . wfile . write ( '<STR_LIT:\r\n>' ) <EOL> shutil . copyfileobj ( response . body , self . wfile , COPY_BLOCK_SIZE ) <EOL> except ( IOError , OSError ) , e : <EOL> if e . errno not in [ errno . EPIPE , os_compat . WSAECONNABORTED ] : <EOL> raise e <EOL> except socket . error , e : <EOL> logging . error ( "<STR_LIT>" % str ( e ) ) <EOL> self . server . stop_serving_forever ( ) <EOL> def log_error ( self , format , * args ) : <EOL> """<STR_LIT>""" <EOL> logging . error ( format , * args ) <EOL> def log_message ( self , format , * args ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( self , '<STR_LIT:path>' ) : <EOL> logging . debug ( format , * args ) <EOL> else : <EOL> logging . info ( format , * args ) <EOL> def log_request ( self , code = '<STR_LIT:->' , size = '<STR_LIT:->' ) : <EOL> """<STR_LIT>""" <EOL> BaseHTTPServer . BaseHTTPRequestHandler . log_request ( self , code , size ) <EOL> if code == '<STR_LIT:->' : <EOL> code = <NUM_LIT:0> <EOL> if size == '<STR_LIT:->' : <EOL> size = <NUM_LIT:0> <EOL> logservice . logs_buffer ( ) . flush ( ) <EOL> self . _log_record_writer . write ( self . command , self . path , code , size , <EOL> self . request_version ) <EOL> return DevAppServerRequestHandler <EOL> def ReadAppConfig ( appinfo_path , parse_app_config = appinfo_includes . Parse ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> appinfo_file = file ( appinfo_path , '<STR_LIT:r>' ) <EOL> except IOError , unused_e : <EOL> raise InvalidAppConfigError ( <EOL> '<STR_LIT>' % appinfo_path ) <EOL> try : <EOL> return parse_app_config ( appinfo_file ) <EOL> finally : <EOL> appinfo_file . close ( ) <EOL> def _StaticFilePathRe ( url_map ) : <EOL> """<STR_LIT>""" <EOL> handler_type = url_map . GetHandlerType ( ) <EOL> if handler_type == '<STR_LIT>' : <EOL> return url_map . upload + '<STR_LIT:$>' <EOL> elif handler_type == '<STR_LIT>' : <EOL> path = url_map . static_dir . rstrip ( os . path . sep ) <EOL> return path + re . escape ( os . path . sep ) + r'<STR_LIT>' <EOL> assert False , '<STR_LIT>' <EOL> def CreateURLMatcherFromMaps ( config , <EOL> root_path , <EOL> url_map_list , <EOL> module_dict , <EOL> default_expiration , <EOL> create_url_matcher = URLMatcher , <EOL> create_cgi_dispatcher = CGIDispatcher , <EOL> create_file_dispatcher = FileDispatcher , <EOL> create_path_adjuster = PathAdjuster , <EOL> normpath = os . path . normpath ) : <EOL> """<STR_LIT>""" <EOL> if config and config . handlers and not url_map_list : <EOL> url_map_list = config . handlers <EOL> url_matcher = create_url_matcher ( ) <EOL> path_adjuster = create_path_adjuster ( root_path ) <EOL> cgi_dispatcher = create_cgi_dispatcher ( config , module_dict , <EOL> root_path , path_adjuster ) <EOL> static_file_config_matcher = StaticFileConfigMatcher ( url_map_list , <EOL> default_expiration ) <EOL> file_dispatcher = create_file_dispatcher ( config , path_adjuster , <EOL> static_file_config_matcher ) <EOL> FakeFile . SetStaticFileConfigMatcher ( static_file_config_matcher ) <EOL> for url_map in url_map_list : <EOL> admin_only = url_map . login == appinfo . LOGIN_ADMIN <EOL> requires_login = url_map . login == appinfo . LOGIN_REQUIRED or admin_only <EOL> auth_fail_action = url_map . auth_fail_action <EOL> handler_type = url_map . GetHandlerType ( ) <EOL> if handler_type == appinfo . HANDLER_SCRIPT : <EOL> dispatcher = cgi_dispatcher <EOL> elif handler_type in ( appinfo . STATIC_FILES , appinfo . STATIC_DIR ) : <EOL> dispatcher = file_dispatcher <EOL> else : <EOL> raise InvalidAppConfigError ( '<STR_LIT>' % handler_type ) <EOL> regex = url_map . url <EOL> path = url_map . GetHandler ( ) <EOL> if handler_type == appinfo . STATIC_DIR : <EOL> if regex [ - <NUM_LIT:1> ] == r'<STR_LIT:/>' : <EOL> regex = regex [ : - <NUM_LIT:1> ] <EOL> if path [ - <NUM_LIT:1> ] == os . path . sep : <EOL> path = path [ : - <NUM_LIT:1> ] <EOL> regex = '<STR_LIT:/>' . join ( ( re . escape ( regex ) , '<STR_LIT>' ) ) <EOL> if os . path . sep == '<STR_LIT:\\>' : <EOL> backref = r'<STR_LIT>' <EOL> else : <EOL> backref = r'<STR_LIT>' <EOL> path = ( normpath ( path ) . replace ( '<STR_LIT:\\>' , '<STR_LIT>' ) + <EOL> os . path . sep + backref ) <EOL> url_matcher . AddURL ( regex , <EOL> dispatcher , <EOL> path , <EOL> requires_login , admin_only , auth_fail_action ) <EOL> return url_matcher <EOL> class AppConfigCache ( object ) : <EOL> """<STR_LIT>""" <EOL> path = None <EOL> mtime = None <EOL> config = None <EOL> matcher = None <EOL> def LoadAppConfig ( root_path , <EOL> module_dict , <EOL> cache = None , <EOL> static_caching = True , <EOL> read_app_config = ReadAppConfig , <EOL> create_matcher = CreateURLMatcherFromMaps , <EOL> default_partition = None ) : <EOL> """<STR_LIT>""" <EOL> for appinfo_path in [ os . path . join ( root_path , '<STR_LIT>' ) , <EOL> os . path . join ( root_path , '<STR_LIT>' ) ] : <EOL> if os . path . isfile ( appinfo_path ) : <EOL> if cache is not None : <EOL> mtime = os . path . getmtime ( appinfo_path ) <EOL> if cache . path == appinfo_path and cache . mtime == mtime : <EOL> return ( cache . config , cache . matcher , True ) <EOL> cache . config = cache . matcher = cache . path = None <EOL> cache . mtime = mtime <EOL> config = read_app_config ( appinfo_path , appinfo_includes . Parse ) <EOL> if static_caching : <EOL> if config . default_expiration : <EOL> default_expiration = config . default_expiration <EOL> else : <EOL> default_expiration = '<STR_LIT:0>' <EOL> else : <EOL> default_expiration = None <EOL> matcher = create_matcher ( config , <EOL> root_path , <EOL> config . handlers , <EOL> module_dict , <EOL> default_expiration ) <EOL> FakeFile . SetSkippedFiles ( config . skip_files ) <EOL> if cache is not None : <EOL> cache . path = appinfo_path <EOL> cache . config = config <EOL> cache . matcher = matcher <EOL> return config , matcher , False <EOL> raise AppConfigNotFoundError ( <EOL> '<STR_LIT>' % ( root_path , ) ) <EOL> class ReservedPathFilter ( ) : <EOL> """<STR_LIT>""" <EOL> reserved_paths = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> def __init__ ( self , inbound_services ) : <EOL> self . inbound_services = inbound_services <EOL> def ExcludePath ( self , path ) : <EOL> """<STR_LIT>""" <EOL> skip = False <EOL> for reserved_path in self . reserved_paths . keys ( ) : <EOL> if path . startswith ( reserved_path ) : <EOL> if ( not self . inbound_services or <EOL> self . reserved_paths [ reserved_path ] not in self . inbound_services ) : <EOL> return ( True , self . reserved_paths [ reserved_path ] ) <EOL> return ( False , None ) <EOL> def CreateInboundServiceFilter ( inbound_services ) : <EOL> return ReservedPathFilter ( inbound_services ) <EOL> def ReadCronConfig ( croninfo_path , parse_cron_config = croninfo . LoadSingleCron ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> croninfo_file = file ( croninfo_path , '<STR_LIT:r>' ) <EOL> except IOError , e : <EOL> raise InvalidAppConfigError ( <EOL> '<STR_LIT>' <EOL> % ( croninfo_path , e ) ) <EOL> try : <EOL> return parse_cron_config ( croninfo_file ) <EOL> finally : <EOL> croninfo_file . close ( ) <EOL> def _RemoveFile ( file_path ) : <EOL> if file_path and os . path . lexists ( file_path ) : <EOL> logging . info ( '<STR_LIT>' , file_path ) <EOL> try : <EOL> os . remove ( file_path ) <EOL> except OSError , e : <EOL> logging . warning ( '<STR_LIT>' , e ) <EOL> def SetupStubs ( app_id , ** config ) : <EOL> """<STR_LIT>""" <EOL> root_path = config . get ( '<STR_LIT>' , None ) <EOL> login_url = config [ '<STR_LIT>' ] <EOL> datastore_path = config [ '<STR_LIT>' ] <EOL> clear_datastore = config [ '<STR_LIT>' ] <EOL> prospective_search_path = config . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> clear_prospective_search = config . get ( '<STR_LIT>' , False ) <EOL> use_sqlite = config . get ( '<STR_LIT>' , False ) <EOL> high_replication = config . get ( '<STR_LIT>' , False ) <EOL> require_indexes = config . get ( '<STR_LIT>' , False ) <EOL> mysql_host = config . get ( '<STR_LIT>' , None ) <EOL> mysql_port = config . get ( '<STR_LIT>' , <NUM_LIT> ) <EOL> mysql_user = config . get ( '<STR_LIT>' , None ) <EOL> mysql_password = config . get ( '<STR_LIT>' , None ) <EOL> mysql_socket = config . get ( '<STR_LIT>' , None ) <EOL> smtp_host = config . get ( '<STR_LIT>' , None ) <EOL> smtp_port = config . get ( '<STR_LIT>' , <NUM_LIT> ) <EOL> smtp_user = config . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> smtp_password = config . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> enable_sendmail = config . get ( '<STR_LIT>' , False ) <EOL> show_mail_body = config . get ( '<STR_LIT>' , False ) <EOL> remove = config . get ( '<STR_LIT>' , os . remove ) <EOL> disable_task_running = config . get ( '<STR_LIT>' , False ) <EOL> task_retry_seconds = config . get ( '<STR_LIT>' , <NUM_LIT:30> ) <EOL> logs_path = config . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> trusted = config . get ( '<STR_LIT>' , False ) <EOL> clear_search_index = config . get ( '<STR_LIT>' , False ) <EOL> search_index_path = config . get ( '<STR_LIT>' , None ) <EOL> _use_atexit_for_datastore_stub = config . get ( '<STR_LIT>' , <EOL> False ) <EOL> port_sqlite_data = config . get ( '<STR_LIT>' , False ) <EOL> serve_port = int ( config . get ( '<STR_LIT>' , <NUM_LIT> ) ) <EOL> serve_address = config . get ( '<STR_LIT>' , '<STR_LIT:localhost>' ) <EOL> xmpp_path = config [ '<STR_LIT>' ] <EOL> uaserver_path = config [ '<STR_LIT>' ] <EOL> login_server = config [ '<STR_LIT>' ] <EOL> cookie_secret = config [ '<STR_LIT>' ] <EOL> os . environ [ '<STR_LIT>' ] = app_id <EOL> os . environ [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> if clear_prospective_search and prospective_search_path : <EOL> _RemoveFile ( prospective_search_path ) <EOL> if clear_datastore : <EOL> _RemoveFile ( datastore_path ) <EOL> if clear_search_index : <EOL> _RemoveFile ( search_index_path ) <EOL> apiproxy_stub_map . apiproxy = apiproxy_stub_map . APIProxyStubMap ( ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> app_identity_stub . AppIdentityServiceStub ( ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> capability_stub . CapabilityServiceStub ( ) ) <EOL> datastore = datastore_distributed . DatastoreDistributed ( <EOL> app_id , datastore_path , require_indexes = require_indexes , <EOL> trusted = trusted , root_path = root_path ) <EOL> apiproxy_stub_map . apiproxy . ReplaceStub ( <EOL> '<STR_LIT>' , datastore ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> mail_stub . MailServiceStub ( smtp_host , <EOL> smtp_port , <EOL> smtp_user , <EOL> smtp_password , <EOL> enable_sendmail = enable_sendmail , <EOL> show_mail_body = show_mail_body ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> memcache_distributed . MemcacheService ( ) ) <EOL> hash_secret = hashlib . sha1 ( app_id + '<STR_LIT:/>' + cookie_secret ) . hexdigest ( ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> taskqueue_distributed . TaskQueueServiceStub ( app_id , serve_address , serve_port ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> urlfetch_stub . URLFetchServiceStub ( ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> xmpp_service_real . XmppService ( domain = xmpp_path , uaserver = uaserver_path ) ) <EOL> from google . appengine import api <EOL> sys . modules [ '<STR_LIT>' ] = rdbms_mysqldb <EOL> api . rdbms = rdbms_mysqldb <EOL> rdbms_mysqldb . SetConnectKwargs ( host = mysql_host , port = mysql_port , <EOL> user = mysql_user , passwd = mysql_password , <EOL> unix_socket = mysql_socket ) <EOL> fixed_login_url = '<STR_LIT>' % ( login_url , <EOL> dev_appserver_login . CONTINUE_PARAM ) <EOL> fixed_logout_url = '<STR_LIT>' % ( login_server , <EOL> DASHBOARD_HTTPS_PORT , dev_appserver_login . CONTINUE_PARAM ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT:user>' , <EOL> user_service_stub . UserServiceStub ( login_url = fixed_login_url , <EOL> logout_url = fixed_logout_url ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> channel_service_stub . ChannelServiceStub ( ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> prospective_search_stub . ProspectiveSearchStub ( <EOL> prospective_search_path , <EOL> apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> _remote_socket_stub . RemoteSocketServiceStub ( ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> simple_search_stub . SearchServiceStub ( index_file = search_index_path ) ) <EOL> try : <EOL> from google . appengine . api . images import images_stub <EOL> host_prefix = '<STR_LIT>' % ( serve_address , serve_port ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> images_stub . ImagesServiceStub ( host_prefix = host_prefix ) ) <EOL> except ImportError , e : <EOL> logging . warning ( '<STR_LIT>' <EOL> '<STR_LIT>' , e ) <EOL> from google . appengine . api . images import images_not_implemented_stub <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> images_not_implemented_stub . ImagesNotImplementedServiceStub ( ) ) <EOL> blob_storage = datastore_blob_storage . DatastoreBlobStorage ( <EOL> app_id ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> blobstore_stub . BlobstoreServiceStub ( blob_storage ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT:file>' , <EOL> file_service_stub . FileServiceStub ( blob_storage ) ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( <EOL> '<STR_LIT>' , <EOL> logservice_stub . LogServiceStub ( True ) ) <EOL> system_service_stub = system_stub . SystemServiceStub ( ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( '<STR_LIT>' , system_service_stub ) <EOL> def TearDownStubs ( ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def CreateImplicitMatcher ( <EOL> config , <EOL> module_dict , <EOL> root_path , <EOL> login_url , <EOL> create_path_adjuster = PathAdjuster , <EOL> create_local_dispatcher = LocalCGIDispatcher , <EOL> create_cgi_dispatcher = CGIDispatcher , <EOL> get_blob_storage = dev_appserver_blobstore . GetBlobStorage ) : <EOL> """<STR_LIT>""" <EOL> url_matcher = URLMatcher ( ) <EOL> path_adjuster = create_path_adjuster ( root_path ) <EOL> def _StatusChecker ( ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> status_dispatcher = create_local_dispatcher ( config , sys . modules , path_adjuster , <EOL> _StatusChecker ) <EOL> url_matcher . AddURL ( '<STR_LIT>' , <EOL> status_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_REDIRECT ) <EOL> def _HandleQuit ( ) : <EOL> raise KeyboardInterrupt <EOL> quit_dispatcher = create_local_dispatcher ( config , sys . modules , path_adjuster , <EOL> _HandleQuit ) <EOL> url_matcher . AddURL ( '<STR_LIT>' , <EOL> quit_dispatcher , <EOL> '<STR_LIT>' , <EOL> True , <EOL> True , <EOL> appinfo . AUTH_FAIL_ACTION_REDIRECT ) <EOL> login_dispatcher = create_local_dispatcher ( config , sys . modules , path_adjuster , <EOL> dev_appserver_login . main ) <EOL> url_matcher . AddURL ( login_url , <EOL> login_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_REDIRECT ) <EOL> admin_dispatcher = create_cgi_dispatcher ( config , module_dict , root_path , <EOL> path_adjuster ) <EOL> url_matcher . AddURL ( '<STR_LIT>' , <EOL> admin_dispatcher , <EOL> DEVEL_CONSOLE_PATH , <EOL> True , <EOL> True , <EOL> appinfo . AUTH_FAIL_ACTION_REDIRECT ) <EOL> upload_dispatcher = dev_appserver_blobstore . CreateUploadDispatcher ( <EOL> get_blob_storage ) <EOL> url_matcher . AddURL ( dev_appserver_blobstore . UPLOAD_URL_PATTERN , <EOL> upload_dispatcher , <EOL> '<STR_LIT>' , <EOL> True , <EOL> True , <EOL> appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED ) <EOL> blobimage_dispatcher = dev_appserver_blobimage . CreateBlobImageDispatcher ( <EOL> apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) ) <EOL> url_matcher . AddURL ( dev_appserver_blobimage . BLOBIMAGE_URL_PATTERN , <EOL> blobimage_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED ) <EOL> oauth_dispatcher = dev_appserver_oauth . CreateOAuthDispatcher ( ) <EOL> url_matcher . AddURL ( dev_appserver_oauth . OAUTH_URL_PATTERN , <EOL> oauth_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED ) <EOL> channel_dispatcher = dev_appserver_channel . CreateChannelDispatcher ( <EOL> apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) ) <EOL> url_matcher . AddURL ( dev_appserver_channel . CHANNEL_JSAPI_PATTERN , <EOL> channel_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED ) <EOL> apiserver_dispatcher = dev_appserver_apiserver . CreateApiserverDispatcher ( ) <EOL> url_matcher . AddURL ( dev_appserver_apiserver . API_SERVING_PATTERN , <EOL> apiserver_dispatcher , <EOL> '<STR_LIT>' , <EOL> False , <EOL> False , <EOL> appinfo . AUTH_FAIL_ACTION_UNAUTHORIZED ) <EOL> return url_matcher <EOL> def FetchAllEntitites ( ) : <EOL> """<STR_LIT>""" <EOL> ns = list ( datastore . Query ( '<STR_LIT>' ) . Run ( ) ) <EOL> original_ns = namespace_manager . get_namespace ( ) <EOL> entities_set = [ ] <EOL> for namespace in ns : <EOL> namespace_manager . set_namespace ( namespace . key ( ) . name ( ) ) <EOL> kinds_list = list ( datastore . Query ( '<STR_LIT>' ) . Run ( ) ) <EOL> for kind_entity in kinds_list : <EOL> ents = list ( datastore . Query ( kind_entity . key ( ) . name ( ) ) . Run ( ) ) <EOL> for ent in ents : <EOL> entities_set . append ( ent ) <EOL> namespace_manager . set_namespace ( original_ns ) <EOL> return entities_set <EOL> def PutAllEntities ( entities ) : <EOL> """<STR_LIT>""" <EOL> for entity in entities : <EOL> datastore . Put ( entity ) <EOL> def PortAllEntities ( datastore_path ) : <EOL> """<STR_LIT>""" <EOL> previous_stub = apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) <EOL> try : <EOL> app_id = os . environ [ '<STR_LIT>' ] <EOL> apiproxy_stub_map . apiproxy = apiproxy_stub_map . APIProxyStubMap ( ) <EOL> datastore_stub = datastore_file_stub . DatastoreFileStub ( <EOL> app_id , datastore_path , trusted = True ) <EOL> apiproxy_stub_map . apiproxy . RegisterStub ( '<STR_LIT>' , datastore_stub ) <EOL> entities = FetchAllEntitites ( ) <EOL> sqlite_datastore_stub = datastore_sqlite_stub . DatastoreSqliteStub ( app_id , <EOL> datastore_path + '<STR_LIT>' , trusted = True ) <EOL> apiproxy_stub_map . apiproxy . ReplaceStub ( '<STR_LIT>' , <EOL> sqlite_datastore_stub ) <EOL> PutAllEntities ( entities ) <EOL> sqlite_datastore_stub . Close ( ) <EOL> finally : <EOL> apiproxy_stub_map . apiproxy . ReplaceStub ( '<STR_LIT>' , previous_stub ) <EOL> shutil . copy ( datastore_path , datastore_path + '<STR_LIT>' ) <EOL> _RemoveFile ( datastore_path ) <EOL> shutil . move ( datastore_path + '<STR_LIT>' , datastore_path ) <EOL> def CreateServer ( root_path , <EOL> login_url , <EOL> port , <EOL> template_dir = None , <EOL> serve_address = '<STR_LIT>' , <EOL> allow_skipped_files = False , <EOL> static_caching = True , <EOL> python_path_list = sys . path , <EOL> sdk_dir = SDK_ROOT , <EOL> default_partition = None , <EOL> frontend_port = None , <EOL> interactive_console = True , <EOL> secret_hash = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> absolute_root_path = os . path . realpath ( root_path ) <EOL> FakeFile . SetAllowedPaths ( absolute_root_path , <EOL> [ sdk_dir ] ) <EOL> FakeFile . SetAllowSkippedFiles ( allow_skipped_files ) <EOL> handler_class = CreateRequestHandler ( absolute_root_path , <EOL> login_url , <EOL> static_caching , <EOL> default_partition , <EOL> interactive_console , <EOL> secret_hash = secret_hash ) <EOL> if absolute_root_path not in python_path_list : <EOL> python_path_list . insert ( <NUM_LIT:0> , absolute_root_path ) <EOL> server = HTTPServerWithScheduler ( ( serve_address , port ) , handler_class ) <EOL> queue_stub = apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) <EOL> if queue_stub and hasattr ( queue_stub , '<STR_LIT>' ) : <EOL> queue_stub . StartBackgroundExecution ( ) <EOL> channel_stub = apiproxy_stub_map . apiproxy . GetStub ( '<STR_LIT>' ) <EOL> if channel_stub : <EOL> channel_stub . _add_event = server . AddEvent <EOL> channel_stub . _update_event = server . UpdateEvent <EOL> server . frontend_hostport = '<STR_LIT>' % ( serve_address or '<STR_LIT:localhost>' , <EOL> frontend_port or port ) <EOL> return server <EOL> class HTTPServerWithScheduler ( BaseHTTPServer . HTTPServer ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , server_address , request_handler_class ) : <EOL> """<STR_LIT>""" <EOL> BaseHTTPServer . HTTPServer . __init__ ( self , server_address , <EOL> request_handler_class ) <EOL> self . _events = [ ] <EOL> self . _stopped = False <EOL> def handle_request ( self ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( self , "<STR_LIT>" ) : <EOL> self . _handle_request_noblock ( ) <EOL> else : <EOL> BaseHTTPServer . HTTPServer . handle_request ( self ) <EOL> def get_request ( self , time_func = time . time , select_func = select . select ) : <EOL> """<STR_LIT>""" <EOL> while True : <EOL> if self . _events : <EOL> current_time = time_func ( ) <EOL> next_eta = self . _events [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> delay = next_eta - current_time <EOL> else : <EOL> delay = DEFAULT_SELECT_DELAY <EOL> readable , _ , _ = select_func ( [ self . socket ] , [ ] , [ ] , max ( delay , <NUM_LIT:0> ) ) <EOL> if readable : <EOL> return self . socket . accept ( ) <EOL> current_time = time_func ( ) <EOL> if self . _events and current_time >= self . _events [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] : <EOL> runnable = heapq . heappop ( self . _events ) [ <NUM_LIT:1> ] <EOL> request_tuple = runnable ( ) <EOL> if request_tuple : <EOL> return request_tuple <EOL> def serve_forever ( self ) : <EOL> """<STR_LIT>""" <EOL> while not self . _stopped : <EOL> self . handle_request ( ) <EOL> self . server_close ( ) <EOL> def stop_serving_forever ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _stopped = True <EOL> def AddEvent ( self , eta , runnable , service = None , event_id = None ) : <EOL> """<STR_LIT>""" <EOL> heapq . heappush ( self . _events , ( eta , runnable , service , event_id ) ) <EOL> def UpdateEvent ( self , service , event_id , eta ) : <EOL> """<STR_LIT>""" <EOL> for id in xrange ( len ( self . _events ) ) : <EOL> item = self . _events [ id ] <EOL> if item [ <NUM_LIT:2> ] == service and item [ <NUM_LIT:3> ] == event_id : <EOL> item = ( eta , item [ <NUM_LIT:1> ] , item [ <NUM_LIT:2> ] , item [ <NUM_LIT:3> ] ) <EOL> del ( self . _events [ id ] ) <EOL> heapq . heappush ( self . _events , item ) <EOL> break </s>
|
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import getpass <EOL> import itertools <EOL> import os <EOL> import os . path <EOL> import sys <EOL> import tempfile <EOL> import unittest <EOL> import google <EOL> import mox <EOL> from google . appengine . tools . devappserver2 import devappserver2 <EOL> class WinError ( Exception ) : <EOL> pass <EOL> class GenerateStoragePathsTest ( unittest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . mox = mox . Mox ( ) <EOL> self . mox . StubOutWithMock ( getpass , '<STR_LIT>' ) <EOL> self . mox . StubOutWithMock ( tempfile , '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . mox . UnsetStubs ( ) <EOL> @ unittest . skipUnless ( sys . platform . startswith ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> def test_windows ( self ) : <EOL> tempfile . gettempdir ( ) . AndReturn ( '<STR_LIT>' ) <EOL> self . mox . ReplayAll ( ) <EOL> self . assertEqual ( <EOL> [ os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) ] , <EOL> list ( itertools . islice ( devappserver2 . _generate_storage_paths ( '<STR_LIT>' ) , <EOL> <NUM_LIT:3> ) ) ) <EOL> self . mox . VerifyAll ( ) <EOL> @ unittest . skipIf ( sys . platform . startswith ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> def test_working_getuser ( self ) : <EOL> getpass . getuser ( ) . AndReturn ( '<STR_LIT>' ) <EOL> tempfile . gettempdir ( ) . AndReturn ( '<STR_LIT>' ) <EOL> self . mox . ReplayAll ( ) <EOL> self . assertEqual ( <EOL> [ os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) ] , <EOL> list ( itertools . islice ( devappserver2 . _generate_storage_paths ( '<STR_LIT>' ) , <EOL> <NUM_LIT:3> ) ) ) <EOL> self . mox . VerifyAll ( ) <EOL> @ unittest . skipIf ( sys . platform . startswith ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> def test_broken_getuser ( self ) : <EOL> getpass . getuser ( ) . AndRaise ( Exception ( ) ) <EOL> tempfile . gettempdir ( ) . AndReturn ( '<STR_LIT>' ) <EOL> self . mox . ReplayAll ( ) <EOL> self . assertEqual ( <EOL> [ os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( '<STR_LIT>' , '<STR_LIT>' ) ] , <EOL> list ( itertools . islice ( devappserver2 . _generate_storage_paths ( '<STR_LIT>' ) , <EOL> <NUM_LIT:3> ) ) ) <EOL> self . mox . VerifyAll ( ) <EOL> class GetStoragePathTest ( unittest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . mox = mox . Mox ( ) <EOL> self . mox . StubOutWithMock ( devappserver2 , '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . mox . UnsetStubs ( ) <EOL> def test_no_path_given_directory_does_not_exist ( self ) : <EOL> path = tempfile . mkdtemp ( ) <EOL> os . rmdir ( path ) <EOL> devappserver2 . _generate_storage_paths ( '<STR_LIT>' ) . AndReturn ( [ path ] ) <EOL> self . mox . ReplayAll ( ) <EOL> self . assertEqual ( <EOL> path , <EOL> devappserver2 . _get_storage_path ( None , '<STR_LIT>' ) ) <EOL> self . mox . VerifyAll ( ) <EOL> self . assertTrue ( os . path . isdir ( path ) ) <EOL> def test_no_path_given_directory_exists ( self ) : <EOL> path1 = tempfile . mkdtemp ( ) <EOL> os . chmod ( path1 , <NUM_LIT:0> <NUM_LIT> ) <EOL> path2 = tempfile . mkdtemp ( ) <EOL> devappserver2 . _generate_storage_paths ( '<STR_LIT>' ) . AndReturn ( <EOL> [ path1 , path2 ] ) <EOL> self . mox . ReplayAll ( ) <EOL> if sys . platform == '<STR_LIT:win32>' : <EOL> expected_path = path1 <EOL> else : <EOL> expected_path = path2 <EOL> self . assertEqual ( <EOL> expected_path , <EOL> devappserver2 . _get_storage_path ( None , '<STR_LIT>' ) ) <EOL> self . mox . VerifyAll ( ) <EOL> def test_path_given_does_not_exist ( self ) : <EOL> path = tempfile . mkdtemp ( ) <EOL> os . rmdir ( path ) <EOL> self . assertEqual ( <EOL> path , <EOL> devappserver2 . _get_storage_path ( path , '<STR_LIT>' ) ) <EOL> self . assertTrue ( os . path . isdir ( path ) ) <EOL> def test_path_given_not_directory ( self ) : <EOL> _ , path = tempfile . mkstemp ( ) <EOL> self . assertRaises ( <EOL> IOError , <EOL> devappserver2 . _get_storage_path , path , '<STR_LIT>' ) <EOL> def test_path_given_exists ( self ) : <EOL> path = tempfile . mkdtemp ( ) <EOL> self . assertEqual ( <EOL> path , <EOL> devappserver2 . _get_storage_path ( path , '<STR_LIT>' ) ) <EOL> class PortParserTest ( unittest . TestCase ) : <EOL> def test_valid_port ( self ) : <EOL> self . assertEqual ( <NUM_LIT> , devappserver2 . PortParser ( ) ( '<STR_LIT>' ) ) <EOL> def test_port_zero_allowed ( self ) : <EOL> self . assertEqual ( <NUM_LIT:0> , devappserver2 . PortParser ( ) ( '<STR_LIT:0>' ) ) <EOL> def test_port_zero_not_allowed ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , <EOL> devappserver2 . PortParser ( allow_port_zero = False ) , '<STR_LIT:0>' ) <EOL> def test_negative_port ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , devappserver2 . PortParser ( ) , <EOL> '<STR_LIT>' ) <EOL> def test_port_too_high ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , devappserver2 . PortParser ( ) , <EOL> '<STR_LIT>' ) <EOL> def test_port_max_value ( self ) : <EOL> self . assertEqual ( <NUM_LIT> , devappserver2 . PortParser ( ) ( '<STR_LIT>' ) ) <EOL> def test_not_an_int ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , devappserver2 . PortParser ( ) , <EOL> '<STR_LIT>' ) <EOL> class ParseMaxServerInstancesTest ( unittest . TestCase ) : <EOL> def test_single_valid_arg ( self ) : <EOL> self . assertEqual ( <NUM_LIT:1> , devappserver2 . parse_max_server_instances ( '<STR_LIT:1>' ) ) <EOL> def test_single_zero_arg ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , <EOL> devappserver2 . parse_max_server_instances , '<STR_LIT:0>' ) <EOL> def test_single_nonint_arg ( self ) : <EOL> self . assertRaises ( argparse . ArgumentTypeError , <EOL> devappserver2 . parse_max_server_instances , '<STR_LIT>' ) <EOL> def test_multiple_valid_args ( self ) : <EOL> self . assertEqual ( <EOL> { '<STR_LIT:default>' : <NUM_LIT:10> , <EOL> '<STR_LIT:foo>' : <NUM_LIT:5> } , <EOL> devappserver2 . parse_max_server_instances ( '<STR_LIT>' ) ) <EOL> def test_multiple_non_colon ( self ) : <EOL> self . assertRaises ( <EOL> argparse . ArgumentTypeError , <EOL> devappserver2 . parse_max_server_instances , '<STR_LIT>' ) <EOL> def test_multiple_non_int ( self ) : <EOL> self . assertRaises ( <EOL> argparse . ArgumentTypeError , <EOL> devappserver2 . parse_max_server_instances , '<STR_LIT>' ) <EOL> def test_duplicate_servers ( self ) : <EOL> self . assertRaises ( <EOL> argparse . ArgumentTypeError , <EOL> devappserver2 . parse_max_server_instances , '<STR_LIT>' ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> unittest . main ( ) </s>
|
<s> """<STR_LIT>""" <EOL> import logging <EOL> import os <EOL> import os . path <EOL> import shutil <EOL> import sys <EOL> import tempfile <EOL> import unittest <EOL> from google . appengine . tools . devappserver2 import inotify_file_watcher <EOL> @ unittest . skipUnless ( sys . platform . startswith ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> class TestInotifyFileWatcher ( unittest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . _directory = tempfile . mkdtemp ( ) <EOL> self . _junk_directory = tempfile . mkdtemp ( ) <EOL> self . _watcher = inotify_file_watcher . InotifyFileWatcher ( self . _directory ) <EOL> logging . debug ( '<STR_LIT>' , <EOL> self . _directory , self . _junk_directory ) <EOL> def tearDown ( self ) : <EOL> self . _watcher . quit ( ) <EOL> shutil . rmtree ( self . _directory ) <EOL> shutil . rmtree ( self . _junk_directory ) <EOL> def _create_file ( self , relative_path ) : <EOL> realpath = os . path . realpath ( os . path . join ( self . _directory , relative_path ) ) <EOL> with open ( realpath , '<STR_LIT:w>' ) : <EOL> pass <EOL> return realpath <EOL> def _create_directory ( self , relative_path ) : <EOL> realpath = os . path . realpath ( os . path . join ( self . _directory , relative_path ) ) <EOL> os . mkdir ( realpath ) <EOL> return realpath <EOL> def _create_directory_tree ( self , path , num_directories ) : <EOL> """<STR_LIT>""" <EOL> assert num_directories >= <NUM_LIT:0> <EOL> if not num_directories : <EOL> return <EOL> self . _create_directory ( path ) <EOL> num_directories -= <NUM_LIT:1> <EOL> for i in range ( <NUM_LIT:4> , <NUM_LIT:0> , - <NUM_LIT:1> ) : <EOL> sub_dir_size = num_directories / i <EOL> self . _create_directory_tree ( os . path . join ( path , '<STR_LIT>' % i ) , sub_dir_size ) <EOL> num_directories -= sub_dir_size <EOL> def test_file_created ( self ) : <EOL> self . _watcher . start ( ) <EOL> path = self . _create_file ( '<STR_LIT:test>' ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_file_modified ( self ) : <EOL> path = self . _create_file ( '<STR_LIT:test>' ) <EOL> self . _watcher . start ( ) <EOL> with open ( path , '<STR_LIT:w>' ) as f : <EOL> f . write ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_file_read ( self ) : <EOL> path = self . _create_file ( '<STR_LIT:test>' ) <EOL> with open ( path , '<STR_LIT:w>' ) as f : <EOL> f . write ( '<STR_LIT>' ) <EOL> self . _watcher . start ( ) <EOL> with open ( path , '<STR_LIT:r>' ) as f : <EOL> f . read ( ) <EOL> self . assertEqual ( <EOL> set ( ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_file_deleted ( self ) : <EOL> path = self . _create_file ( '<STR_LIT:test>' ) <EOL> self . _watcher . start ( ) <EOL> os . remove ( path ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_file_renamed ( self ) : <EOL> source = self . _create_file ( '<STR_LIT:test>' ) <EOL> target = os . path . join ( os . path . dirname ( source ) , '<STR_LIT>' ) <EOL> self . _watcher . start ( ) <EOL> os . rename ( source , target ) <EOL> self . assertEqual ( <EOL> set ( [ source , target ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_create_directory ( self ) : <EOL> self . _watcher . start ( ) <EOL> directory = self . _create_directory ( '<STR_LIT:test>' ) <EOL> self . assertEqual ( <EOL> set ( [ directory ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_file_created_in_directory ( self ) : <EOL> directory = self . _create_directory ( '<STR_LIT:test>' ) <EOL> self . _watcher . start ( ) <EOL> path = self . _create_file ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_move_directory ( self ) : <EOL> source = self . _create_directory ( '<STR_LIT:test>' ) <EOL> target = os . path . join ( os . path . dirname ( source ) , '<STR_LIT>' ) <EOL> self . _watcher . start ( ) <EOL> os . rename ( source , target ) <EOL> self . assertEqual ( <EOL> set ( [ source , target ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_move_directory_out_of_watched ( self ) : <EOL> source = self . _create_directory ( '<STR_LIT:test>' ) <EOL> target = os . path . join ( self . _junk_directory , '<STR_LIT:test>' ) <EOL> self . _watcher . start ( ) <EOL> os . rename ( source , target ) <EOL> self . assertEqual ( <EOL> set ( [ source ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> with open ( os . path . join ( target , '<STR_LIT:file>' ) , '<STR_LIT:w>' ) : <EOL> pass <EOL> self . assertEqual ( <EOL> set ( [ ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_move_directory_into_watched ( self ) : <EOL> source = os . path . join ( self . _junk_directory , '<STR_LIT:source>' ) <EOL> target = os . path . join ( self . _directory , '<STR_LIT:target>' ) <EOL> os . mkdir ( source ) <EOL> self . _watcher . start ( ) <EOL> os . rename ( source , target ) <EOL> self . assertEqual ( <EOL> set ( [ target ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> file_path = os . path . join ( target , '<STR_LIT:file>' ) <EOL> with open ( file_path , '<STR_LIT>' ) : <EOL> pass <EOL> self . assertEqual ( <EOL> set ( [ file_path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_directory_deleted ( self ) : <EOL> path = self . _create_directory ( '<STR_LIT:test>' ) <EOL> self . _watcher . start ( ) <EOL> os . rmdir ( path ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_subdirectory_deleted ( self ) : <EOL> """<STR_LIT>""" <EOL> path = self . _create_directory ( '<STR_LIT:test>' ) <EOL> sub_path = self . _create_directory ( '<STR_LIT>' ) <EOL> self . _watcher . start ( ) <EOL> self . assertEqual ( <EOL> set ( [ sub_path ] ) , <EOL> self . _watcher . _directory_to_subdirs [ path ] ) <EOL> os . rmdir ( sub_path ) <EOL> self . assertEqual ( <EOL> set ( [ sub_path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> self . assertEqual ( <EOL> set ( ) , <EOL> self . _watcher . _directory_to_subdirs [ path ] ) <EOL> os . rmdir ( path ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_symlink ( self ) : <EOL> sym_target = os . path . join ( self . _directory , '<STR_LIT:test>' ) <EOL> os . mkdir ( os . path . join ( self . _junk_directory , '<STR_LIT>' ) ) <EOL> self . _watcher . start ( ) <EOL> os . symlink ( self . _junk_directory , sym_target ) <EOL> self . assertEqual ( <EOL> set ( [ sym_target ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> with open ( os . path . join ( self . _junk_directory , '<STR_LIT>' ) , '<STR_LIT:w>' ) : <EOL> pass <EOL> self . assertEqual ( <EOL> set ( [ os . path . join ( self . _directory , '<STR_LIT:test>' , '<STR_LIT>' ) ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> os . remove ( sym_target ) <EOL> self . assertEqual ( <EOL> set ( [ sym_target ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> with open ( os . path . join ( self . _junk_directory , '<STR_LIT>' , '<STR_LIT>' ) , '<STR_LIT:w>' ) : <EOL> pass <EOL> self . assertEqual ( <EOL> set ( ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> def test_many_directories ( self ) : <EOL> self . _create_directory_tree ( '<STR_LIT>' , num_directories = <NUM_LIT> ) <EOL> self . _watcher . start ( ) <EOL> path = self . _create_file ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> set ( [ path ] ) , <EOL> self . _watcher . _get_changed_paths ( ) ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> unittest . main ( ) </s>
|
<s> """<STR_LIT>""" <EOL> import os <EOL> import signal <EOL> import time <EOL> import unittest <EOL> import google <EOL> import mox <EOL> from google . appengine . tools . devappserver2 import shutdown <EOL> class ShutdownTest ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . mox = mox . Mox ( ) <EOL> self . mox . StubOutWithMock ( os , '<STR_LIT>' ) <EOL> shutdown . _shutting_down = False <EOL> shutdown . _num_terminate_requests = <NUM_LIT:0> <EOL> self . _sigint_handler = signal . getsignal ( signal . SIGINT ) <EOL> self . _sigterm_handler = signal . getsignal ( signal . SIGTERM ) <EOL> def tearDown ( self ) : <EOL> self . mox . UnsetStubs ( ) <EOL> signal . signal ( signal . SIGINT , self . _sigint_handler ) <EOL> signal . signal ( signal . SIGTERM , self . _sigterm_handler ) <EOL> def test_async_quit ( self ) : <EOL> self . mox . ReplayAll ( ) <EOL> shutdown . async_quit ( ) <EOL> self . assertTrue ( shutdown . _shutting_down ) <EOL> self . mox . VerifyAll ( ) <EOL> def test_async_terminate ( self ) : <EOL> self . mox . ReplayAll ( ) <EOL> shutdown . _async_terminate ( ) <EOL> self . assertTrue ( shutdown . _shutting_down ) <EOL> shutdown . _async_terminate ( ) <EOL> self . mox . VerifyAll ( ) <EOL> def test_async_terminate_abort ( self ) : <EOL> os . abort ( ) <EOL> self . mox . ReplayAll ( ) <EOL> shutdown . _async_terminate ( ) <EOL> self . assertTrue ( shutdown . _shutting_down ) <EOL> shutdown . _async_terminate ( ) <EOL> shutdown . _async_terminate ( ) <EOL> self . mox . VerifyAll ( ) <EOL> def test_install_signal_handlers ( self ) : <EOL> shutdown . install_signal_handlers ( ) <EOL> self . assertEqual ( shutdown . _async_terminate , signal . getsignal ( signal . SIGINT ) ) <EOL> self . assertEqual ( shutdown . _async_terminate , <EOL> signal . getsignal ( signal . SIGTERM ) ) <EOL> def test_wait_until_shutdown ( self ) : <EOL> self . mox . StubOutWithMock ( time , '<STR_LIT>' ) <EOL> time . sleep ( <NUM_LIT:1> ) . WithSideEffects ( lambda _ : shutdown . async_quit ( ) ) <EOL> self . mox . ReplayAll ( ) <EOL> shutdown . wait_until_shutdown ( ) <EOL> self . mox . VerifyAll ( ) <EOL> def test_wait_until_shutdown_raise_interrupted_io ( self ) : <EOL> def quit_and_raise ( * _ ) : <EOL> shutdown . async_quit ( ) <EOL> raise IOError <EOL> self . mox . StubOutWithMock ( time , '<STR_LIT>' ) <EOL> time . sleep ( <NUM_LIT:1> ) . WithSideEffects ( quit_and_raise ) <EOL> self . mox . ReplayAll ( ) <EOL> shutdown . wait_until_shutdown ( ) <EOL> self . mox . VerifyAll ( ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> unittest . main ( ) </s>
|
<s> """<STR_LIT>""" <EOL> import logging <EOL> import Queue <EOL> import threading <EOL> import time <EOL> logger = logging . getLogger ( '<STR_LIT>' ) <EOL> class ReQueue ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , <EOL> queue_capacity , <EOL> requeue_capacity = None , <EOL> queue_factory = Queue . Queue , <EOL> get_time = time . time ) : <EOL> """<STR_LIT>""" <EOL> if requeue_capacity is None : <EOL> requeue_capacity = queue_capacity <EOL> self . get_time = get_time <EOL> self . queue = queue_factory ( queue_capacity ) <EOL> self . requeue = queue_factory ( requeue_capacity ) <EOL> self . lock = threading . Lock ( ) <EOL> self . put_cond = threading . Condition ( self . lock ) <EOL> self . get_cond = threading . Condition ( self . lock ) <EOL> def _DoWithTimeout ( self , <EOL> action , <EOL> exc , <EOL> wait_cond , <EOL> done_cond , <EOL> lock , <EOL> timeout = None , <EOL> block = True ) : <EOL> """<STR_LIT>""" <EOL> if timeout is not None and timeout < <NUM_LIT:0.0> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> if not block : <EOL> timeout = <NUM_LIT:0.0> <EOL> result = None <EOL> success = False <EOL> start_time = self . get_time ( ) <EOL> lock . acquire ( ) <EOL> try : <EOL> while not success : <EOL> try : <EOL> result = action ( ) <EOL> success = True <EOL> except Exception , e : <EOL> if not isinstance ( e , exc ) : <EOL> raise e <EOL> if timeout is not None : <EOL> elapsed_time = self . get_time ( ) - start_time <EOL> timeout -= elapsed_time <EOL> if timeout <= <NUM_LIT:0.0> : <EOL> raise e <EOL> wait_cond . wait ( timeout ) <EOL> finally : <EOL> if success : <EOL> done_cond . notify ( ) <EOL> lock . release ( ) <EOL> return result <EOL> def put ( self , item , block = True , timeout = None ) : <EOL> """<STR_LIT>""" <EOL> def PutAction ( ) : <EOL> self . queue . put ( item , block = False ) <EOL> self . _DoWithTimeout ( PutAction , <EOL> Queue . Full , <EOL> self . get_cond , <EOL> self . put_cond , <EOL> self . lock , <EOL> timeout = timeout , <EOL> block = block ) <EOL> def reput ( self , item , block = True , timeout = None ) : <EOL> """<STR_LIT>""" <EOL> def ReputAction ( ) : <EOL> self . requeue . put ( item , block = False ) <EOL> self . _DoWithTimeout ( ReputAction , <EOL> Queue . Full , <EOL> self . get_cond , <EOL> self . put_cond , <EOL> self . lock , <EOL> timeout = timeout , <EOL> block = block ) <EOL> def get ( self , block = True , timeout = None ) : <EOL> """<STR_LIT>""" <EOL> def GetAction ( ) : <EOL> try : <EOL> result = self . requeue . get ( block = False ) <EOL> self . requeue . task_done ( ) <EOL> except Queue . Empty : <EOL> result = self . queue . get ( block = False ) <EOL> return result <EOL> return self . _DoWithTimeout ( GetAction , <EOL> Queue . Empty , <EOL> self . put_cond , <EOL> self . get_cond , <EOL> self . lock , <EOL> timeout = timeout , <EOL> block = block ) <EOL> def join ( self ) : <EOL> """<STR_LIT>""" <EOL> self . queue . join ( ) <EOL> def task_done ( self ) : <EOL> """<STR_LIT>""" <EOL> self . queue . task_done ( ) <EOL> def empty ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . queue . empty ( ) and self . requeue . empty ( ) <EOL> def get_nowait ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . get ( block = False ) <EOL> def qsize ( self ) : <EOL> return self . queue . qsize ( ) + self . requeue . qsize ( ) </s>
|
<s> """<STR_LIT>""" </s>
|
<s> """<STR_LIT>""" <EOL> from sqlalchemy . orm import collections <EOL> import pyamf <EOL> from pyamf . adapters import util <EOL> pyamf . add_type ( collections . InstrumentedList , util . to_list ) <EOL> pyamf . add_type ( collections . InstrumentedDict , util . to_dict ) <EOL> pyamf . add_type ( collections . InstrumentedSet , util . to_set ) </s>
|
<s> """<STR_LIT>""" <EOL> import unittest <EOL> import sys <EOL> import os <EOL> import datetime <EOL> import pyamf <EOL> from pyamf . tests import util <EOL> try : <EOL> import django <EOL> except ImportError : <EOL> django = None <EOL> if django and django . VERSION < ( <NUM_LIT:1> , <NUM_LIT:0> ) : <EOL> django = None <EOL> try : <EOL> reload ( settings ) <EOL> except NameError : <EOL> from pyamf . tests . adapters . django_app import settings <EOL> context = None <EOL> create_test_db = None <EOL> destroy_test_db = None <EOL> management = None <EOL> setup_test_environment = None <EOL> teardown_test_environment = None <EOL> models = None <EOL> adapter = None <EOL> def init_django ( ) : <EOL> """<STR_LIT>""" <EOL> global django , management , create_test_db , destroy_test_db <EOL> global setup_test_environment , teardown_test_environment <EOL> if not django : <EOL> return <EOL> from django . core import management <EOL> project_dir = management . setup_environ ( settings ) <EOL> sys . path . insert ( <NUM_LIT:0> , project_dir ) <EOL> try : <EOL> from django . test . utils import create_test_db , destroy_test_db <EOL> except ImportError : <EOL> from django . db import connection <EOL> create_test_db = connection . creation . create_test_db <EOL> destroy_test_db = connection . creation . destroy_test_db <EOL> from django . test . utils import setup_test_environment , teardown_test_environment <EOL> return True <EOL> def setUpModule ( ) : <EOL> """<STR_LIT>""" <EOL> global context , models , adapter <EOL> context = { <EOL> '<STR_LIT>' : sys . path [ : ] , <EOL> '<STR_LIT>' : sys . modules . copy ( ) , <EOL> '<STR_LIT>' : os . environ . copy ( ) , <EOL> } <EOL> if init_django ( ) : <EOL> from pyamf . tests . adapters . django_app . adapters import models <EOL> from pyamf . adapters import _django_db_models_base as adapter <EOL> setup_test_environment ( ) <EOL> settings . DATABASE_NAME = create_test_db ( <NUM_LIT:0> , True ) <EOL> def teadDownModule ( ) : <EOL> teardown_test_environment ( ) <EOL> sys . path = context [ '<STR_LIT>' ] <EOL> util . replace_dict ( context [ '<STR_LIT>' ] , sys . modules ) <EOL> util . replace_dict ( context [ '<STR_LIT>' ] , os . environ ) <EOL> destroy_test_db ( settings . DATABASE_NAME , <NUM_LIT:2> ) <EOL> class BaseTestCase ( unittest . TestCase ) : <EOL> """<STR_LIT:U+0020>""" <EOL> def setUp ( self ) : <EOL> if not django : <EOL> self . skipTest ( "<STR_LIT>" ) <EOL> class TypeMapTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_objects_all ( self ) : <EOL> encoder = pyamf . get_encoder ( pyamf . AMF0 ) <EOL> encoder . writeElement ( models . SimplestModel . objects . all ( ) ) <EOL> self . assertEqual ( encoder . stream . getvalue ( ) , '<STR_LIT>' ) <EOL> encoder = pyamf . get_encoder ( pyamf . AMF3 ) <EOL> encoder . writeElement ( models . SimplestModel . objects . all ( ) ) <EOL> self . assertEqual ( encoder . stream . getvalue ( ) , '<STR_LIT>' ) <EOL> def test_NOT_PROVIDED ( self ) : <EOL> from django . db . models import fields <EOL> self . assertEqual ( pyamf . encode ( fields . NOT_PROVIDED , encoding = pyamf . AMF0 ) . getvalue ( ) , <EOL> '<STR_LIT>' ) <EOL> encoder = pyamf . get_encoder ( pyamf . AMF3 ) <EOL> encoder . writeElement ( fields . NOT_PROVIDED ) <EOL> self . assertEqual ( encoder . stream . getvalue ( ) , '<STR_LIT:\x00>' ) <EOL> class ClassAliasTestCase ( BaseTestCase ) : <EOL> def test_time ( self ) : <EOL> x = models . TimeClass ( ) <EOL> x . t = datetime . time ( <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) <EOL> x . d = datetime . date ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> ) <EOL> x . dt = datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) <EOL> alias = adapter . DjangoClassAlias ( models . TimeClass , None ) <EOL> attrs = alias . getEncodableAttributes ( x ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:d>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:0> , <NUM_LIT:0> ) , <EOL> '<STR_LIT>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) , <EOL> '<STR_LIT:t>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) <EOL> } ) <EOL> y = models . TimeClass ( ) <EOL> alias . applyAttributes ( y , { <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:d>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:0> , <NUM_LIT:0> ) , <EOL> '<STR_LIT>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) , <EOL> '<STR_LIT:t>' : datetime . datetime ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) <EOL> } ) <EOL> self . assertEqual ( y . id , None ) <EOL> self . assertEqual ( y . d , datetime . date ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> ) ) <EOL> self . assertEqual ( y . dt , datetime . datetime ( <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) ) <EOL> self . assertEqual ( y . t , datetime . time ( <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) ) <EOL> y = models . TimeClass ( ) <EOL> alias . applyAttributes ( y , { <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:d>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT:t>' : None <EOL> } ) <EOL> self . assertEqual ( y . id , None ) <EOL> self . assertEqual ( y . d , None ) <EOL> self . assertEqual ( y . dt , None ) <EOL> self . assertEqual ( y . t , None ) <EOL> def test_undefined ( self ) : <EOL> from django . db import models <EOL> from django . db . models import fields <EOL> class UndefinedClass ( models . Model ) : <EOL> pass <EOL> alias = adapter . DjangoClassAlias ( UndefinedClass , None ) <EOL> x = UndefinedClass ( ) <EOL> alias . applyAttributes ( x , { <EOL> '<STR_LIT:id>' : pyamf . Undefined <EOL> } ) <EOL> self . assertEqual ( x . id , fields . NOT_PROVIDED ) <EOL> x . id = fields . NOT_PROVIDED <EOL> attrs = alias . getEncodableAttributes ( x ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:id>' : pyamf . Undefined } ) <EOL> def test_non_field_prop ( self ) : <EOL> from django . db import models <EOL> class Book ( models . Model ) : <EOL> def _get_number_of_odd_pages ( self ) : <EOL> return <NUM_LIT> <EOL> numberOfOddPages = property ( _get_number_of_odd_pages ) <EOL> alias = adapter . DjangoClassAlias ( Book , '<STR_LIT>' ) <EOL> x = Book ( ) <EOL> self . assertEqual ( alias . getEncodableAttributes ( x ) , <EOL> { '<STR_LIT>' : <NUM_LIT> , '<STR_LIT:id>' : None } ) <EOL> alias . applyAttributes ( x , { '<STR_LIT>' : <NUM_LIT> , '<STR_LIT:id>' : None } ) <EOL> self . assertEqual ( x . numberOfOddPages , <NUM_LIT> ) <EOL> def test_dynamic ( self ) : <EOL> """<STR_LIT>""" <EOL> alias = adapter . DjangoClassAlias ( models . SimplestModel , '<STR_LIT>' ) <EOL> x = models . SimplestModel ( ) <EOL> x . spam = '<STR_LIT>' <EOL> self . assertEqual ( alias . getEncodableAttributes ( x ) , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:id>' : None } ) <EOL> alias . applyAttributes ( x , { '<STR_LIT>' : '<STR_LIT:foo>' , '<STR_LIT:id>' : None } ) <EOL> self . assertEqual ( x . spam , '<STR_LIT:foo>' ) <EOL> def test_properties ( self ) : <EOL> """<STR_LIT>""" <EOL> from django . db import models <EOL> class Foob ( models . Model ) : <EOL> def _get_days ( self ) : <EOL> return <NUM_LIT:1> <EOL> def _set_days ( self , val ) : <EOL> assert <NUM_LIT:1> == val <EOL> days = property ( _get_days , _set_days ) <EOL> alias = adapter . DjangoClassAlias ( Foob , '<STR_LIT>' ) <EOL> x = Foob ( ) <EOL> self . assertEqual ( x . days , <NUM_LIT:1> ) <EOL> self . assertEqual ( alias . getEncodableAttributes ( x ) , <EOL> { '<STR_LIT>' : <NUM_LIT:1> , '<STR_LIT:id>' : None } ) <EOL> alias . applyAttributes ( x , { '<STR_LIT:id>' : None } ) <EOL> class ForeignKeyTestCase ( BaseTestCase ) : <EOL> def test_one_to_many ( self ) : <EOL> r = models . Reporter ( first_name = '<STR_LIT>' , last_name = '<STR_LIT>' , email = '<STR_LIT>' ) <EOL> r . save ( ) <EOL> self . addCleanup ( r . delete ) <EOL> r2 = models . Reporter ( first_name = '<STR_LIT>' , last_name = '<STR_LIT>' , email = '<STR_LIT>' ) <EOL> r2 . save ( ) <EOL> self . addCleanup ( r2 . delete ) <EOL> a = models . Article ( headline = "<STR_LIT>" , reporter = r ) <EOL> a . save ( ) <EOL> self . addCleanup ( a . delete ) <EOL> self . assertEqual ( a . id , <NUM_LIT:1> ) <EOL> del a <EOL> a = models . Article . objects . filter ( pk = <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> self . assertFalse ( '<STR_LIT>' in a . __dict__ ) <EOL> a . reporter <EOL> self . assertTrue ( '<STR_LIT>' in a . __dict__ ) <EOL> del a <EOL> a = models . Article . objects . filter ( pk = <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> alias = adapter . DjangoClassAlias ( models . Article , defer = True ) <EOL> self . assertFalse ( hasattr ( alias , '<STR_LIT>' ) ) <EOL> attrs = alias . getEncodableAttributes ( a ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : [ ] <EOL> } ) <EOL> self . assertFalse ( '<STR_LIT>' in a . __dict__ ) <EOL> self . assertEqual ( pyamf . encode ( a , encoding = pyamf . AMF3 ) . getvalue ( ) , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> del a <EOL> a = models . Article . objects . select_related ( '<STR_LIT>' ) . filter ( pk = <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> alias = adapter . DjangoClassAlias ( models . Article , defer = True ) <EOL> self . assertFalse ( hasattr ( alias , '<STR_LIT>' ) ) <EOL> self . assertEqual ( alias . getEncodableAttributes ( a ) , { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : r , <EOL> '<STR_LIT>' : [ ] <EOL> } ) <EOL> self . assertTrue ( '<STR_LIT>' in a . __dict__ ) <EOL> self . assertEqual ( pyamf . encode ( a , encoding = pyamf . AMF3 ) . getvalue ( ) , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> def test_many_to_many ( self ) : <EOL> p1 = models . Publication ( id = None , title = '<STR_LIT>' ) <EOL> p1 . save ( ) <EOL> p2 = models . Publication ( id = None , title = '<STR_LIT>' ) <EOL> p2 . save ( ) <EOL> p3 = models . Publication ( id = None , title = '<STR_LIT>' ) <EOL> p3 . save ( ) <EOL> self . addCleanup ( p1 . delete ) <EOL> self . addCleanup ( p2 . delete ) <EOL> self . addCleanup ( p3 . delete ) <EOL> a1 = models . Article ( id = None , headline = '<STR_LIT>' ) <EOL> a1 . save ( ) <EOL> self . addCleanup ( a1 . delete ) <EOL> self . assertEqual ( a1 . id , <NUM_LIT:1> ) <EOL> a1 . publications . add ( p1 ) <EOL> pub_alias = adapter . DjangoClassAlias ( models . Publication , None ) <EOL> art_alias = adapter . DjangoClassAlias ( models . Article , None ) <EOL> test_publication = models . Publication . objects . filter ( pk = <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> test_article = models . Article . objects . filter ( pk = <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> attrs = pub_alias . getEncodableAttributes ( test_publication ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:id>' : <NUM_LIT:1> , '<STR_LIT:title>' : u'<STR_LIT>' } ) <EOL> attrs = art_alias . getEncodableAttributes ( test_article ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : [ p1 ] <EOL> } ) <EOL> x = models . Article ( ) <EOL> art_alias . applyAttributes ( x , { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : [ p1 ] <EOL> } ) <EOL> self . assertEqual ( x . headline , u'<STR_LIT>' ) <EOL> self . assertEqual ( x . id , <NUM_LIT:1> ) <EOL> self . assertEqual ( list ( x . publications . all ( ) ) , [ p1 ] ) <EOL> y = models . Article ( ) <EOL> attrs = art_alias . getDecodableAttributes ( y , { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:0> , <EOL> '<STR_LIT>' : [ ] <EOL> } ) <EOL> self . assertEqual ( attrs , { '<STR_LIT>' : u'<STR_LIT>' } ) <EOL> def test_nullable_foreign_keys ( self ) : <EOL> x = models . SimplestModel ( ) <EOL> x . save ( ) <EOL> self . addCleanup ( x . delete ) <EOL> nfk_alias = adapter . DjangoClassAlias ( models . NullForeignKey , None ) <EOL> bfk_alias = adapter . DjangoClassAlias ( models . BlankForeignKey , None ) <EOL> nfk = models . NullForeignKey ( ) <EOL> attrs = nfk_alias . getEncodableAttributes ( nfk ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:id>' : None } ) <EOL> bfk = models . BlankForeignKey ( ) <EOL> attrs = bfk_alias . getEncodableAttributes ( bfk ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:id>' : None } ) <EOL> def test_static_relation ( self ) : <EOL> """<STR_LIT>""" <EOL> from pyamf import util <EOL> pyamf . register_class ( models . StaticRelation ) <EOL> alias = adapter . DjangoClassAlias ( models . StaticRelation , <EOL> static_attrs = ( '<STR_LIT>' , ) ) <EOL> alias . compile ( ) <EOL> self . assertTrue ( '<STR_LIT>' in alias . relations ) <EOL> self . assertTrue ( '<STR_LIT>' in alias . decodable_properties ) <EOL> self . assertTrue ( '<STR_LIT>' in alias . static_attrs ) <EOL> x = models . StaticRelation ( ) <EOL> alias . getDecodableAttributes ( x , { '<STR_LIT:id>' : None , '<STR_LIT>' : '<STR_LIT:foo>' } ) <EOL> class I18NTestCase ( BaseTestCase ) : <EOL> def test_encode ( self ) : <EOL> from django . utils . translation import ugettext_lazy <EOL> self . assertEqual ( pyamf . encode ( ugettext_lazy ( '<STR_LIT>' ) ) . getvalue ( ) , <EOL> '<STR_LIT>' ) <EOL> class PKTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_behaviour ( self ) : <EOL> p = models . Publication ( id = None , title = '<STR_LIT>' ) <EOL> a = models . Article ( id = None , headline = '<STR_LIT>' ) <EOL> self . assertRaises ( ValueError , lambda a , p : a . publications . add ( p ) , a , p ) <EOL> p . save ( ) <EOL> a . save ( ) <EOL> self . addCleanup ( p . delete ) <EOL> self . addCleanup ( a . delete ) <EOL> self . assertEqual ( a . id , <NUM_LIT:1> ) <EOL> article_alias = adapter . DjangoClassAlias ( models . Article , None ) <EOL> x = models . Article ( ) <EOL> article_alias . applyAttributes ( x , { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : [ p ] <EOL> } ) <EOL> self . assertEqual ( x . headline , '<STR_LIT>' ) <EOL> self . assertEqual ( x . id , <NUM_LIT:1> ) <EOL> self . assertEqual ( list ( x . publications . all ( ) ) , [ p ] ) <EOL> def test_none ( self ) : <EOL> """<STR_LIT>""" <EOL> alias = adapter . DjangoClassAlias ( models . SimplestModel , None ) <EOL> x = models . SimplestModel ( ) <EOL> self . assertEqual ( x . id , None ) <EOL> alias . applyAttributes ( x , { <EOL> '<STR_LIT:id>' : <NUM_LIT:0> <EOL> } ) <EOL> self . assertEqual ( x . id , None ) <EOL> def test_no_pk ( self ) : <EOL> """<STR_LIT>""" <EOL> instances = [ models . NotSaved ( name = "<STR_LIT:a>" ) , models . NotSaved ( name = "<STR_LIT:b>" ) ] <EOL> encoded = pyamf . encode ( instances , encoding = pyamf . AMF3 ) . getvalue ( ) <EOL> decoded = pyamf . decode ( encoded , encoding = pyamf . AMF3 ) . next ( ) <EOL> self . assertEqual ( decoded [ <NUM_LIT:0> ] [ '<STR_LIT:name>' ] , '<STR_LIT:a>' ) <EOL> self . assertEqual ( decoded [ <NUM_LIT:1> ] [ '<STR_LIT:name>' ] , '<STR_LIT:b>' ) <EOL> class ModelInheritanceTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_abstract ( self ) : <EOL> alias = adapter . DjangoClassAlias ( models . Student ) <EOL> x = models . Student ( ) <EOL> attrs = alias . getEncodableAttributes ( x ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:name>' : '<STR_LIT>' <EOL> } ) <EOL> def test_concrete ( self ) : <EOL> alias = adapter . DjangoClassAlias ( models . Place ) <EOL> x = models . Place ( ) <EOL> attrs = alias . getEncodableAttributes ( x ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:address>' : '<STR_LIT>' <EOL> } ) <EOL> alias = adapter . DjangoClassAlias ( models . Restaurant ) <EOL> x = models . Restaurant ( ) <EOL> attrs = alias . getEncodableAttributes ( x ) <EOL> self . assertEqual ( attrs , { <EOL> '<STR_LIT:id>' : None , <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:address>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : False <EOL> } ) <EOL> class MockFile ( object ) : <EOL> """<STR_LIT>""" <EOL> def chunks ( self ) : <EOL> return [ ] <EOL> def __len__ ( self ) : <EOL> return <NUM_LIT:0> <EOL> def read ( self , n ) : <EOL> return '<STR_LIT>' <EOL> class FieldsTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_file ( self ) : <EOL> alias = adapter . DjangoClassAlias ( models . FileModel ) <EOL> i = models . FileModel ( ) <EOL> i . file . save ( '<STR_LIT:bar>' , MockFile ( ) ) <EOL> self . addCleanup ( i . file . delete ) <EOL> i . save ( ) <EOL> attrs = alias . getEncodableAttributes ( i ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:text>' : '<STR_LIT>' , '<STR_LIT:id>' : <NUM_LIT:1> , '<STR_LIT:file>' : u'<STR_LIT>' } ) <EOL> attrs = alias . getDecodableAttributes ( i , attrs ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:text>' : '<STR_LIT>' } ) <EOL> class ImageTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> try : <EOL> import PIL <EOL> except ImportError : <EOL> self . skipTest ( "<STR_LIT>" ) <EOL> BaseTestCase . setUp ( self ) <EOL> def test_image ( self ) : <EOL> alias = adapter . DjangoClassAlias ( models . Profile ) <EOL> i = models . Profile ( ) <EOL> i . file . save ( '<STR_LIT:bar>' , MockFile ( ) ) <EOL> self . addCleanup ( i . file . delete ) <EOL> i . save ( ) <EOL> self . addCleanup ( i . delete ) <EOL> attrs = alias . getEncodableAttributes ( i ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:text>' : '<STR_LIT>' , '<STR_LIT:id>' : <NUM_LIT:1> , '<STR_LIT:file>' : u'<STR_LIT>' } ) <EOL> attrs = alias . getDecodableAttributes ( i , attrs ) <EOL> self . assertEqual ( attrs , { '<STR_LIT:text>' : '<STR_LIT>' } ) <EOL> class ReferenceTestCase ( BaseTestCase , util . EncoderMixIn ) : <EOL> """<STR_LIT>""" <EOL> amf_type = pyamf . AMF3 <EOL> def setUp ( self ) : <EOL> BaseTestCase . setUp ( self ) <EOL> util . EncoderMixIn . setUp ( self ) <EOL> def test_not_referenced ( self ) : <EOL> """<STR_LIT>""" <EOL> f = models . ParentReference ( ) <EOL> f . name = '<STR_LIT:foo>' <EOL> b = models . ChildReference ( ) <EOL> b . name = '<STR_LIT:bar>' <EOL> f . save ( ) <EOL> b . foo = f <EOL> b . save ( ) <EOL> f . bar = b <EOL> f . save ( ) <EOL> self . addCleanup ( f . delete ) <EOL> self . addCleanup ( b . delete ) <EOL> self . assertEqual ( f . id , <NUM_LIT:1> ) <EOL> foo = models . ParentReference . objects . select_related ( ) . get ( id = <NUM_LIT:1> ) <EOL> self . assertFalse ( foo . bar . foo is foo ) <EOL> def test_referenced_encode ( self ) : <EOL> f = models . ParentReference ( ) <EOL> f . name = '<STR_LIT:foo>' <EOL> b = models . ChildReference ( ) <EOL> b . name = '<STR_LIT:bar>' <EOL> f . save ( ) <EOL> b . foo = f <EOL> b . save ( ) <EOL> f . bar = b <EOL> f . save ( ) <EOL> self . addCleanup ( f . delete ) <EOL> self . addCleanup ( b . delete ) <EOL> self . assertEqual ( f . id , <NUM_LIT:1> ) <EOL> foo = models . ParentReference . objects . select_related ( ) . get ( id = <NUM_LIT:1> ) <EOL> foo . bar . foo <EOL> self . assertEncoded ( foo , '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> class AuthTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_user ( self ) : <EOL> from django . contrib . auth import models <EOL> alias = pyamf . get_class_alias ( models . User ) <EOL> self . assertEqual ( alias , '<STR_LIT>' ) <EOL> self . assertEqual ( alias . exclude_attrs , ( '<STR_LIT>' , '<STR_LIT:password>' ) ) <EOL> self . assertEqual ( alias . readonly_attrs , ( '<STR_LIT:username>' , ) ) <EOL> class DBColumnTestCase ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> BaseTestCase . setUp ( self ) <EOL> self . alias = adapter . DjangoClassAlias ( models . DBColumnModel , None ) <EOL> self . model = models . DBColumnModel ( ) <EOL> def test_encodable_attrs ( self ) : <EOL> def attrs ( ) : <EOL> return self . alias . getEncodableAttributes ( self . model ) <EOL> self . assertEqual ( attrs ( ) , { '<STR_LIT:id>' : None } ) <EOL> x = models . SimplestModel ( ) <EOL> x . save ( ) <EOL> self . addCleanup ( x . delete ) <EOL> self . model . bar = x <EOL> self . assertEqual ( attrs ( ) , { '<STR_LIT:id>' : None , '<STR_LIT:bar>' : x } ) </s>
|
<s> import os <EOL> import warnings <EOL> import cherrypy <EOL> from cherrypy . _cpcompat import iteritems , copykeys , builtins <EOL> class Checker ( object ) : <EOL> """<STR_LIT>""" <EOL> on = True <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . _populate_known_types ( ) <EOL> def __call__ ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . on : <EOL> oldformatwarning = warnings . formatwarning <EOL> warnings . formatwarning = self . formatwarning <EOL> try : <EOL> for name in dir ( self ) : <EOL> if name . startswith ( "<STR_LIT>" ) : <EOL> method = getattr ( self , name ) <EOL> if method and hasattr ( method , '<STR_LIT>' ) : <EOL> method ( ) <EOL> finally : <EOL> warnings . formatwarning = oldformatwarning <EOL> def formatwarning ( self , message , category , filename , lineno , line = None ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % message <EOL> global_config_contained_paths = False <EOL> def check_app_config_entries_dont_start_with_script_name ( self ) : <EOL> """<STR_LIT>""" <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> if not app . config : <EOL> continue <EOL> if sn == '<STR_LIT>' : <EOL> continue <EOL> sn_atoms = sn . strip ( "<STR_LIT:/>" ) . split ( "<STR_LIT:/>" ) <EOL> for key in app . config . keys ( ) : <EOL> key_atoms = key . strip ( "<STR_LIT:/>" ) . split ( "<STR_LIT:/>" ) <EOL> if key_atoms [ : len ( sn_atoms ) ] == sn_atoms : <EOL> warnings . warn ( <EOL> "<STR_LIT>" "<STR_LIT>" % ( sn , key ) ) <EOL> def check_site_config_entries_in_app_config ( self ) : <EOL> """<STR_LIT>""" <EOL> for sn , app in iteritems ( cherrypy . tree . apps ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> msg = [ ] <EOL> for section , entries in iteritems ( app . config ) : <EOL> if section . startswith ( '<STR_LIT:/>' ) : <EOL> for key , value in iteritems ( entries ) : <EOL> for n in ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) : <EOL> if key . startswith ( n ) : <EOL> msg . append ( "<STR_LIT>" % ( section , key , value ) ) <EOL> if msg : <EOL> msg . insert ( <NUM_LIT:0> , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % sn ) <EOL> warnings . warn ( os . linesep . join ( msg ) ) <EOL> def check_skipped_app_config ( self ) : <EOL> """<STR_LIT>""" <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> if not app . config : <EOL> msg = "<STR_LIT>" % sn <EOL> if self . global_config_contained_paths : <EOL> msg += ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> warnings . warn ( msg ) <EOL> return <EOL> def check_app_config_brackets ( self ) : <EOL> """<STR_LIT>""" <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> if not app . config : <EOL> continue <EOL> for key in app . config . keys ( ) : <EOL> if key . startswith ( "<STR_LIT:[>" ) or key . endswith ( "<STR_LIT:]>" ) : <EOL> warnings . warn ( <EOL> "<STR_LIT>" "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( sn , key ) ) <EOL> def check_static_paths ( self ) : <EOL> """<STR_LIT>""" <EOL> request = cherrypy . request <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> request . app = app <EOL> for section in app . config : <EOL> request . get_resource ( section + "<STR_LIT>" ) <EOL> conf = request . config . get <EOL> if conf ( "<STR_LIT>" , False ) : <EOL> msg = "<STR_LIT>" <EOL> root = conf ( "<STR_LIT>" ) <EOL> dir = conf ( "<STR_LIT>" ) <EOL> if dir is None : <EOL> msg = "<STR_LIT>" <EOL> else : <EOL> fulldir = "<STR_LIT>" <EOL> if os . path . isabs ( dir ) : <EOL> fulldir = dir <EOL> if root : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> testdir = os . path . join ( root , dir [ <NUM_LIT:1> : ] ) <EOL> if os . path . exists ( testdir ) : <EOL> msg += ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % testdir ) <EOL> else : <EOL> if not root : <EOL> msg = "<STR_LIT>" <EOL> else : <EOL> fulldir = os . path . join ( root , dir ) <EOL> if not os . path . isabs ( fulldir ) : <EOL> msg = "<STR_LIT>" % fulldir <EOL> if fulldir and not os . path . exists ( fulldir ) : <EOL> if msg : <EOL> msg += "<STR_LIT:\n>" <EOL> msg += ( "<STR_LIT>" <EOL> "<STR_LIT>" % fulldir ) <EOL> if msg : <EOL> warnings . warn ( "<STR_LIT>" <EOL> % ( msg , section , root , dir ) ) <EOL> obsolete = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : ( '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> } <EOL> deprecated = { } <EOL> def _compat ( self , config ) : <EOL> """<STR_LIT>""" <EOL> for section , conf in config . items ( ) : <EOL> if isinstance ( conf , dict ) : <EOL> for k , v in conf . items ( ) : <EOL> if k in self . obsolete : <EOL> warnings . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( k , self . obsolete [ k ] , section ) ) <EOL> elif k in self . deprecated : <EOL> warnings . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( k , self . deprecated [ k ] , section ) ) <EOL> else : <EOL> if section in self . obsolete : <EOL> warnings . warn ( "<STR_LIT>" <EOL> % ( section , self . obsolete [ section ] ) ) <EOL> elif section in self . deprecated : <EOL> warnings . warn ( "<STR_LIT>" <EOL> % ( section , self . deprecated [ section ] ) ) <EOL> def check_compatibility ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _compat ( cherrypy . config ) <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> self . _compat ( app . config ) <EOL> extra_config_namespaces = [ ] <EOL> def _known_ns ( self , app ) : <EOL> ns = [ "<STR_LIT>" ] <EOL> ns . extend ( copykeys ( app . toolboxes ) ) <EOL> ns . extend ( copykeys ( app . namespaces ) ) <EOL> ns . extend ( copykeys ( app . request_class . namespaces ) ) <EOL> ns . extend ( copykeys ( cherrypy . config . namespaces ) ) <EOL> ns += self . extra_config_namespaces <EOL> for section , conf in app . config . items ( ) : <EOL> is_path_section = section . startswith ( "<STR_LIT:/>" ) <EOL> if is_path_section and isinstance ( conf , dict ) : <EOL> for k , v in conf . items ( ) : <EOL> atoms = k . split ( "<STR_LIT:.>" ) <EOL> if len ( atoms ) > <NUM_LIT:1> : <EOL> if atoms [ <NUM_LIT:0> ] not in ns : <EOL> if ( atoms [ <NUM_LIT:0> ] == "<STR_LIT>" and atoms [ <NUM_LIT:1> ] in ns ) : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> % ( k , "<STR_LIT:.>" . join ( atoms [ <NUM_LIT:1> : ] ) , section ) ) <EOL> else : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( k , atoms [ <NUM_LIT:0> ] , section ) ) <EOL> warnings . warn ( msg ) <EOL> elif atoms [ <NUM_LIT:0> ] == "<STR_LIT>" : <EOL> if atoms [ <NUM_LIT:1> ] not in dir ( cherrypy . tools ) : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( k , atoms [ <NUM_LIT:1> ] , section ) ) <EOL> warnings . warn ( msg ) <EOL> def check_config_namespaces ( self ) : <EOL> """<STR_LIT>""" <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> self . _known_ns ( app ) <EOL> known_config_types = { } <EOL> def _populate_known_types ( self ) : <EOL> b = [ x for x in vars ( builtins ) . values ( ) <EOL> if type ( x ) is type ( str ) ] <EOL> def traverse ( obj , namespace ) : <EOL> for name in dir ( obj ) : <EOL> if name == '<STR_LIT>' : <EOL> continue <EOL> vtype = type ( getattr ( obj , name , None ) ) <EOL> if vtype in b : <EOL> self . known_config_types [ namespace + "<STR_LIT:.>" + name ] = vtype <EOL> traverse ( cherrypy . request , "<STR_LIT>" ) <EOL> traverse ( cherrypy . response , "<STR_LIT>" ) <EOL> traverse ( cherrypy . server , "<STR_LIT>" ) <EOL> traverse ( cherrypy . engine , "<STR_LIT>" ) <EOL> traverse ( cherrypy . log , "<STR_LIT>" ) <EOL> def _known_types ( self , config ) : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> for section , conf in config . items ( ) : <EOL> if isinstance ( conf , dict ) : <EOL> for k , v in conf . items ( ) : <EOL> if v is not None : <EOL> expected_type = self . known_config_types . get ( k , None ) <EOL> vtype = type ( v ) <EOL> if expected_type and vtype != expected_type : <EOL> warnings . warn ( msg % ( k , section , vtype . __name__ , <EOL> expected_type . __name__ ) ) <EOL> else : <EOL> k , v = section , conf <EOL> if v is not None : <EOL> expected_type = self . known_config_types . get ( k , None ) <EOL> vtype = type ( v ) <EOL> if expected_type and vtype != expected_type : <EOL> warnings . warn ( msg % ( k , section , vtype . __name__ , <EOL> expected_type . __name__ ) ) <EOL> def check_config_types ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _known_types ( cherrypy . config ) <EOL> for sn , app in cherrypy . tree . apps . items ( ) : <EOL> if not isinstance ( app , cherrypy . Application ) : <EOL> continue <EOL> self . _known_types ( app . config ) <EOL> def check_localhost ( self ) : <EOL> """<STR_LIT>""" <EOL> for k , v in cherrypy . config . items ( ) : <EOL> if k == '<STR_LIT>' and v == '<STR_LIT:localhost>' : <EOL> warnings . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) </s>
|
<s> import warnings <EOL> warnings . warn ( '<STR_LIT>' <EOL> '<STR_LIT>' , <EOL> DeprecationWarning ) <EOL> from cherrypy . lib . httputil import * </s>
|
<s> import cherrypy <EOL> from cherrypy . lib import auth_digest <EOL> from cherrypy . test import helper <EOL> class DigestAuthTest ( helper . CPWebCase ) : <EOL> def setup_server ( ) : <EOL> class Root : <EOL> def index ( self ) : <EOL> return "<STR_LIT>" <EOL> index . exposed = True <EOL> class DigestProtected : <EOL> def index ( self ) : <EOL> return "<STR_LIT>" % cherrypy . request . login <EOL> index . exposed = True <EOL> def fetch_users ( ) : <EOL> return { '<STR_LIT:test>' : '<STR_LIT:test>' } <EOL> get_ha1 = cherrypy . lib . auth_digest . get_ha1_dict_plain ( fetch_users ( ) ) <EOL> conf = { '<STR_LIT>' : { '<STR_LIT>' : True , <EOL> '<STR_LIT>' : '<STR_LIT:localhost>' , <EOL> '<STR_LIT>' : get_ha1 , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT:True>' } } <EOL> root = Root ( ) <EOL> root . digest = DigestProtected ( ) <EOL> cherrypy . tree . mount ( root , config = conf ) <EOL> setup_server = staticmethod ( setup_server ) <EOL> def testPublic ( self ) : <EOL> self . getPage ( "<STR_LIT:/>" ) <EOL> self . assertStatus ( '<STR_LIT>' ) <EOL> self . assertHeader ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> def testDigest ( self ) : <EOL> self . getPage ( "<STR_LIT>" ) <EOL> self . assertStatus ( <NUM_LIT> ) <EOL> value = None <EOL> for k , v in self . headers : <EOL> if k . lower ( ) == "<STR_LIT>" : <EOL> if v . startswith ( "<STR_LIT>" ) : <EOL> value = v <EOL> break <EOL> if value is None : <EOL> self . _handlewebError ( "<STR_LIT>" ) <EOL> value = value [ <NUM_LIT:7> : ] <EOL> items = value . split ( '<STR_LIT:U+002CU+0020>' ) <EOL> tokens = { } <EOL> for item in items : <EOL> key , value = item . split ( '<STR_LIT:=>' ) <EOL> tokens [ key . lower ( ) ] = value <EOL> missing_msg = "<STR_LIT>" <EOL> bad_value_msg = "<STR_LIT>" <EOL> nonce = None <EOL> if '<STR_LIT>' not in tokens : <EOL> self . _handlewebError ( missing_msg % '<STR_LIT>' ) <EOL> elif tokens [ '<STR_LIT>' ] != '<STR_LIT>' : <EOL> self . _handlewebError ( bad_value_msg % ( '<STR_LIT>' , '<STR_LIT>' , tokens [ '<STR_LIT>' ] ) ) <EOL> if '<STR_LIT>' not in tokens : <EOL> self . _handlewebError ( missing_msg % '<STR_LIT>' ) <EOL> else : <EOL> nonce = tokens [ '<STR_LIT>' ] . strip ( '<STR_LIT:">' ) <EOL> if '<STR_LIT>' not in tokens : <EOL> self . _handlewebError ( missing_msg % '<STR_LIT>' ) <EOL> elif tokens [ '<STR_LIT>' ] != '<STR_LIT>' : <EOL> self . _handlewebError ( bad_value_msg % ( '<STR_LIT>' , '<STR_LIT>' , tokens [ '<STR_LIT>' ] ) ) <EOL> if '<STR_LIT>' not in tokens : <EOL> self . _handlewebError ( missing_msg % '<STR_LIT>' ) <EOL> elif tokens [ '<STR_LIT>' ] != '<STR_LIT>' : <EOL> self . _handlewebError ( bad_value_msg % ( '<STR_LIT>' , '<STR_LIT>' , tokens [ '<STR_LIT>' ] ) ) <EOL> get_ha1 = auth_digest . get_ha1_dict_plain ( { '<STR_LIT:test>' : '<STR_LIT:test>' } ) <EOL> base_auth = '<STR_LIT>' <EOL> auth_header = base_auth % ( nonce , '<STR_LIT>' , '<STR_LIT>' ) <EOL> auth = auth_digest . HttpDigestAuthorization ( auth_header , '<STR_LIT:GET>' ) <EOL> ha1 = get_ha1 ( auth . realm , '<STR_LIT:test>' ) <EOL> response = auth . request_digest ( ha1 ) <EOL> auth_header = base_auth % ( nonce , response , '<STR_LIT>' ) <EOL> self . getPage ( '<STR_LIT>' , [ ( '<STR_LIT>' , auth_header ) ] ) <EOL> self . assertStatus ( <NUM_LIT> ) <EOL> base_auth = '<STR_LIT>' <EOL> auth_header = base_auth % ( nonce , '<STR_LIT>' , '<STR_LIT>' ) <EOL> auth = auth_digest . HttpDigestAuthorization ( auth_header , '<STR_LIT:GET>' ) <EOL> ha1 = get_ha1 ( '<STR_LIT:localhost>' , '<STR_LIT:test>' ) <EOL> response = auth . request_digest ( ha1 ) <EOL> auth_header = base_auth % ( nonce , response , '<STR_LIT>' ) <EOL> self . getPage ( '<STR_LIT>' , [ ( '<STR_LIT>' , auth_header ) ] ) <EOL> self . assertStatus ( '<STR_LIT>' ) <EOL> self . assertBody ( "<STR_LIT>" ) </s>
|
<s> import os <EOL> curdir = os . path . join ( os . getcwd ( ) , os . path . dirname ( __file__ ) ) <EOL> import cherrypy <EOL> from cherrypy . test import helper <EOL> class VirtualHostTest ( helper . CPWebCase ) : <EOL> def setup_server ( ) : <EOL> class Root : <EOL> def index ( self ) : <EOL> return "<STR_LIT>" <EOL> index . exposed = True <EOL> def dom4 ( self ) : <EOL> return "<STR_LIT>" <EOL> dom4 . exposed = True <EOL> def method ( self , value ) : <EOL> return "<STR_LIT>" % value <EOL> method . exposed = True <EOL> class VHost : <EOL> def __init__ ( self , sitename ) : <EOL> self . sitename = sitename <EOL> def index ( self ) : <EOL> return "<STR_LIT>" % self . sitename <EOL> index . exposed = True <EOL> def vmethod ( self , value ) : <EOL> return "<STR_LIT>" % value <EOL> vmethod . exposed = True <EOL> def url ( self ) : <EOL> return cherrypy . url ( "<STR_LIT>" ) <EOL> url . exposed = True <EOL> static = cherrypy . tools . staticdir . handler ( section = '<STR_LIT>' , dir = curdir ) <EOL> root = Root ( ) <EOL> root . mydom2 = VHost ( "<STR_LIT>" ) <EOL> root . mydom3 = VHost ( "<STR_LIT>" ) <EOL> hostmap = { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> cherrypy . tree . mount ( root , config = { <EOL> '<STR_LIT:/>' : { '<STR_LIT>' : cherrypy . dispatch . VirtualHost ( ** hostmap ) } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : True , <EOL> '<STR_LIT>' : curdir , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } , <EOL> } ) <EOL> setup_server = staticmethod ( setup_server ) <EOL> def testVirtualHost ( self ) : <EOL> self . getPage ( "<STR_LIT:/>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT:/>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT:/>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT:/>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT>" ) <EOL> self . assertBody ( "<STR_LIT>" ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( "<STR_LIT>" ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] , method = "<STR_LIT:POST>" , <EOL> body = "<STR_LIT>" ) <EOL> self . assertBody ( "<STR_LIT>" ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( "<STR_LIT>" ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertBody ( "<STR_LIT>" % self . scheme ) <EOL> def test_VHost_plus_Static ( self ) : <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertStatus ( '<STR_LIT>' ) <EOL> self . assertHeader ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertStatus ( '<STR_LIT>' ) <EOL> self . assertHeader ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertStatus ( '<STR_LIT>' ) <EOL> self . assertBody ( '<STR_LIT>' ) <EOL> self . getPage ( "<STR_LIT>" , [ ( '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> self . assertStatus ( <NUM_LIT> ) </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import with_statement <EOL> import atexit <EOL> import threading <EOL> import weakref <EOL> from concurrent . futures import _base <EOL> try : <EOL> import queue <EOL> except ImportError : <EOL> import Queue as queue <EOL> __author__ = '<STR_LIT>' <EOL> _threads_queues = weakref . WeakKeyDictionary ( ) <EOL> _shutdown = False <EOL> def _python_exit ( ) : <EOL> global _shutdown <EOL> _shutdown = True <EOL> items = _threads_queues . items ( ) <EOL> for t , q in items : <EOL> q . put ( None ) <EOL> for t , q in items : <EOL> t . join ( ) <EOL> atexit . register ( _python_exit ) <EOL> class _WorkItem ( object ) : <EOL> def __init__ ( self , future , fn , args , kwargs ) : <EOL> self . future = future <EOL> self . fn = fn <EOL> self . args = args <EOL> self . kwargs = kwargs <EOL> def run ( self ) : <EOL> if not self . future . set_running_or_notify_cancel ( ) : <EOL> return <EOL> try : <EOL> result = self . fn ( * self . args , ** self . kwargs ) <EOL> except BaseException as e : <EOL> self . future . set_exception ( e ) <EOL> else : <EOL> self . future . set_result ( result ) <EOL> def _worker ( executor_reference , work_queue ) : <EOL> try : <EOL> while True : <EOL> work_item = work_queue . get ( block = True ) <EOL> if work_item is not None : <EOL> work_item . run ( ) <EOL> continue <EOL> executor = executor_reference ( ) <EOL> if _shutdown or executor is None or executor . _shutdown : <EOL> work_queue . put ( None ) <EOL> return <EOL> del executor <EOL> except BaseException : <EOL> _base . LOGGER . critical ( '<STR_LIT>' , exc_info = True ) <EOL> class ThreadPoolExecutor ( _base . Executor ) : <EOL> def __init__ ( self , max_workers ) : <EOL> """<STR_LIT>""" <EOL> self . _max_workers = max_workers <EOL> self . _work_queue = queue . Queue ( ) <EOL> self . _threads = set ( ) <EOL> self . _shutdown = False <EOL> self . _shutdown_lock = threading . Lock ( ) <EOL> def submit ( self , fn , * args , ** kwargs ) : <EOL> with self . _shutdown_lock : <EOL> if self . _shutdown : <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> f = _base . Future ( ) <EOL> w = _WorkItem ( f , fn , args , kwargs ) <EOL> self . _work_queue . put ( w ) <EOL> self . _adjust_thread_count ( ) <EOL> return f <EOL> submit . __doc__ = _base . Executor . submit . __doc__ <EOL> def _adjust_thread_count ( self ) : <EOL> def weakref_cb ( _ , q = self . _work_queue ) : <EOL> q . put ( None ) <EOL> if len ( self . _threads ) < self . _max_workers : <EOL> t = threading . Thread ( target = _worker , <EOL> args = ( weakref . ref ( self , weakref_cb ) , <EOL> self . _work_queue ) ) <EOL> t . daemon = True <EOL> t . start ( ) <EOL> self . _threads . add ( t ) <EOL> _threads_queues [ t ] = self . _work_queue <EOL> def shutdown ( self , wait = True ) : <EOL> with self . _shutdown_lock : <EOL> self . _shutdown = True <EOL> self . _work_queue . put ( None ) <EOL> if wait : <EOL> for t in self . _threads : <EOL> t . join ( ) <EOL> shutdown . __doc__ = _base . Executor . shutdown . __doc__ </s>
|
<s> from django import template , templatetags <EOL> from django . template import RequestContext <EOL> from django . conf import settings <EOL> from django . contrib . admin . views . decorators import staff_member_required <EOL> from django . db import models <EOL> from django . shortcuts import render_to_response <EOL> from django . core . exceptions import ImproperlyConfigured , ViewDoesNotExist <EOL> from django . http import Http404 , get_host <EOL> from django . core import urlresolvers <EOL> from django . contrib . admin import utils <EOL> from django . contrib . sites . models import Site <EOL> import inspect , os , re <EOL> MODEL_METHODS_EXCLUDE = ( '<STR_LIT:_>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> class GenericSite ( object ) : <EOL> domain = '<STR_LIT>' <EOL> name = '<STR_LIT>' <EOL> def doc_index ( request ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> return render_to_response ( '<STR_LIT>' , context_instance = RequestContext ( request ) ) <EOL> doc_index = staff_member_required ( doc_index ) <EOL> def bookmarklets ( request ) : <EOL> admin_root = request . path [ : - len ( '<STR_LIT>' ) ] <EOL> return render_to_response ( '<STR_LIT>' , { <EOL> '<STR_LIT>' : "<STR_LIT>" % ( request . is_secure ( ) and '<STR_LIT>' or '<STR_LIT:http>' , get_host ( request ) , admin_root ) , <EOL> } , context_instance = RequestContext ( request ) ) <EOL> bookmarklets = staff_member_required ( bookmarklets ) <EOL> def template_tag_index ( request ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> load_all_installed_template_libraries ( ) <EOL> tags = [ ] <EOL> for module_name , library in template . libraries . items ( ) : <EOL> for tag_name , tag_func in library . tags . items ( ) : <EOL> title , body , metadata = utils . parse_docstring ( tag_func . __doc__ ) <EOL> if title : <EOL> title = utils . parse_rst ( title , '<STR_LIT>' , _ ( '<STR_LIT>' ) + tag_name ) <EOL> if body : <EOL> body = utils . parse_rst ( body , '<STR_LIT>' , _ ( '<STR_LIT>' ) + tag_name ) <EOL> for key in metadata : <EOL> metadata [ key ] = utils . parse_rst ( metadata [ key ] , '<STR_LIT>' , _ ( '<STR_LIT>' ) + tag_name ) <EOL> if library in template . builtins : <EOL> tag_library = None <EOL> else : <EOL> tag_library = module_name . split ( '<STR_LIT:.>' ) [ - <NUM_LIT:1> ] <EOL> tags . append ( { <EOL> '<STR_LIT:name>' : tag_name , <EOL> '<STR_LIT:title>' : title , <EOL> '<STR_LIT:body>' : body , <EOL> '<STR_LIT>' : metadata , <EOL> '<STR_LIT>' : tag_library , <EOL> } ) <EOL> return render_to_response ( '<STR_LIT>' , { '<STR_LIT>' : tags } , context_instance = RequestContext ( request ) ) <EOL> template_tag_index = staff_member_required ( template_tag_index ) <EOL> def template_filter_index ( request ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> load_all_installed_template_libraries ( ) <EOL> filters = [ ] <EOL> for module_name , library in template . libraries . items ( ) : <EOL> for filter_name , filter_func in library . filters . items ( ) : <EOL> title , body , metadata = utils . parse_docstring ( filter_func . __doc__ ) <EOL> if title : <EOL> title = utils . parse_rst ( title , '<STR_LIT>' , _ ( '<STR_LIT>' ) + filter_name ) <EOL> if body : <EOL> body = utils . parse_rst ( body , '<STR_LIT>' , _ ( '<STR_LIT>' ) + filter_name ) <EOL> for key in metadata : <EOL> metadata [ key ] = utils . parse_rst ( metadata [ key ] , '<STR_LIT>' , _ ( '<STR_LIT>' ) + filter_name ) <EOL> if library in template . builtins : <EOL> tag_library = None <EOL> else : <EOL> tag_library = module_name . split ( '<STR_LIT:.>' ) [ - <NUM_LIT:1> ] <EOL> filters . append ( { <EOL> '<STR_LIT:name>' : filter_name , <EOL> '<STR_LIT:title>' : title , <EOL> '<STR_LIT:body>' : body , <EOL> '<STR_LIT>' : metadata , <EOL> '<STR_LIT>' : tag_library , <EOL> } ) <EOL> return render_to_response ( '<STR_LIT>' , { '<STR_LIT>' : filters } , context_instance = RequestContext ( request ) ) <EOL> template_filter_index = staff_member_required ( template_filter_index ) <EOL> def view_index ( request ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> if settings . ADMIN_FOR : <EOL> settings_modules = [ __import__ ( m , { } , { } , [ '<STR_LIT>' ] ) for m in settings . ADMIN_FOR ] <EOL> else : <EOL> settings_modules = [ settings ] <EOL> views = [ ] <EOL> for settings_mod in settings_modules : <EOL> urlconf = __import__ ( settings_mod . ROOT_URLCONF , { } , { } , [ '<STR_LIT>' ] ) <EOL> view_functions = extract_views_from_urlpatterns ( urlconf . urlpatterns ) <EOL> if Site . _meta . installed : <EOL> site_obj = Site . objects . get ( pk = settings_mod . SITE_ID ) <EOL> else : <EOL> site_obj = GenericSite ( ) <EOL> for ( func , regex ) in view_functions : <EOL> views . append ( { <EOL> '<STR_LIT:name>' : func . __name__ , <EOL> '<STR_LIT>' : func . __module__ , <EOL> '<STR_LIT>' : settings_mod . SITE_ID , <EOL> '<STR_LIT>' : site_obj , <EOL> '<STR_LIT:url>' : simplify_regex ( regex ) , <EOL> } ) <EOL> return render_to_response ( '<STR_LIT>' , { '<STR_LIT>' : views } , context_instance = RequestContext ( request ) ) <EOL> view_index = staff_member_required ( view_index ) <EOL> def view_detail ( request , view ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> mod , func = urlresolvers . get_mod_func ( view ) <EOL> try : <EOL> view_func = getattr ( __import__ ( mod , { } , { } , [ '<STR_LIT>' ] ) , func ) <EOL> except ( ImportError , AttributeError ) : <EOL> raise Http404 <EOL> title , body , metadata = utils . parse_docstring ( view_func . __doc__ ) <EOL> if title : <EOL> title = utils . parse_rst ( title , '<STR_LIT>' , _ ( '<STR_LIT>' ) + view ) <EOL> if body : <EOL> body = utils . parse_rst ( body , '<STR_LIT>' , _ ( '<STR_LIT>' ) + view ) <EOL> for key in metadata : <EOL> metadata [ key ] = utils . parse_rst ( metadata [ key ] , '<STR_LIT>' , _ ( '<STR_LIT>' ) + view ) <EOL> return render_to_response ( '<STR_LIT>' , { <EOL> '<STR_LIT:name>' : view , <EOL> '<STR_LIT>' : title , <EOL> '<STR_LIT:body>' : body , <EOL> '<STR_LIT>' : metadata , <EOL> } , context_instance = RequestContext ( request ) ) <EOL> view_detail = staff_member_required ( view_detail ) <EOL> def model_index ( request ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> m_list = [ m . _meta for m in models . get_models ( ) ] <EOL> return render_to_response ( '<STR_LIT>' , { '<STR_LIT>' : m_list } , context_instance = RequestContext ( request ) ) <EOL> model_index = staff_member_required ( model_index ) <EOL> def model_detail ( request , app_label , model_name ) : <EOL> if not utils . docutils_is_available : <EOL> return missing_docutils_page ( request ) <EOL> try : <EOL> app_mod = models . get_app ( app_label ) <EOL> except ImproperlyConfigured : <EOL> raise Http404 , _ ( "<STR_LIT>" ) % app_label <EOL> model = None <EOL> for m in models . get_models ( app_mod ) : <EOL> if m . _meta . object_name . lower ( ) == model_name : <EOL> model = m <EOL> break <EOL> if model is None : <EOL> raise Http404 , _ ( "<STR_LIT>" ) % { '<STR_LIT:name>' : model_name , '<STR_LIT:label>' : app_label } <EOL> opts = model . _meta <EOL> fields = [ ] <EOL> for field in opts . fields : <EOL> if isinstance ( field , models . ForeignKey ) : <EOL> data_type = related_object_name = field . rel . to . __name__ <EOL> app_label = field . rel . to . _meta . app_label <EOL> verbose = utils . parse_rst ( ( _ ( "<STR_LIT>" ) % { '<STR_LIT:label>' : app_label , '<STR_LIT:type>' : data_type } ) , '<STR_LIT>' , _ ( '<STR_LIT>' ) + data_type ) <EOL> else : <EOL> data_type = get_readable_field_data_type ( field ) <EOL> verbose = field . verbose_name <EOL> fields . append ( { <EOL> '<STR_LIT:name>' : field . name , <EOL> '<STR_LIT>' : data_type , <EOL> '<STR_LIT>' : verbose , <EOL> '<STR_LIT>' : field . help_text , <EOL> } ) <EOL> for func_name , func in model . __dict__ . items ( ) : <EOL> if ( inspect . isfunction ( func ) and len ( inspect . getargspec ( func ) [ <NUM_LIT:0> ] ) == <NUM_LIT:1> ) : <EOL> try : <EOL> for exclude in MODEL_METHODS_EXCLUDE : <EOL> if func_name . startswith ( exclude ) : <EOL> raise StopIteration <EOL> except StopIteration : <EOL> continue <EOL> verbose = func . __doc__ <EOL> if verbose : <EOL> verbose = utils . parse_rst ( utils . trim_docstring ( verbose ) , '<STR_LIT>' , _ ( '<STR_LIT>' ) + opts . module_name ) <EOL> fields . append ( { <EOL> '<STR_LIT:name>' : func_name , <EOL> '<STR_LIT>' : get_return_data_type ( func_name ) , <EOL> '<STR_LIT>' : verbose , <EOL> } ) <EOL> for rel in opts . get_all_related_objects ( ) : <EOL> verbose = _ ( "<STR_LIT>" ) % { '<STR_LIT:label>' : rel . opts . app_label , '<STR_LIT:name>' : rel . opts . object_name } <EOL> accessor = rel . get_accessor_name ( ) <EOL> fields . append ( { <EOL> '<STR_LIT:name>' : "<STR_LIT>" % accessor , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : utils . parse_rst ( _ ( "<STR_LIT>" ) % verbose , '<STR_LIT>' , _ ( '<STR_LIT>' ) + opts . module_name ) , <EOL> } ) <EOL> fields . append ( { <EOL> '<STR_LIT:name>' : "<STR_LIT>" % accessor , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : utils . parse_rst ( _ ( "<STR_LIT>" ) % verbose , '<STR_LIT>' , _ ( '<STR_LIT>' ) + opts . module_name ) , <EOL> } ) <EOL> return render_to_response ( '<STR_LIT>' , { <EOL> '<STR_LIT:name>' : '<STR_LIT>' % ( opts . app_label , opts . object_name ) , <EOL> '<STR_LIT>' : _ ( "<STR_LIT>" ) % opts . object_name , <EOL> '<STR_LIT:description>' : model . __doc__ , <EOL> '<STR_LIT>' : fields , <EOL> } , context_instance = RequestContext ( request ) ) <EOL> model_detail = staff_member_required ( model_detail ) <EOL> def template_detail ( request , template ) : <EOL> templates = [ ] <EOL> for site_settings_module in settings . ADMIN_FOR : <EOL> settings_mod = __import__ ( site_settings_module , { } , { } , [ '<STR_LIT>' ] ) <EOL> if Site . _meta . installed : <EOL> site_obj = Site . objects . get ( pk = settings_mod . SITE_ID ) <EOL> else : <EOL> site_obj = GenericSite ( ) <EOL> for dir in settings_mod . TEMPLATE_DIRS : <EOL> template_file = os . path . join ( dir , "<STR_LIT>" % template ) <EOL> templates . append ( { <EOL> '<STR_LIT:file>' : template_file , <EOL> '<STR_LIT>' : os . path . exists ( template_file ) , <EOL> '<STR_LIT>' : lambda : os . path . exists ( template_file ) and open ( template_file ) . read ( ) or '<STR_LIT>' , <EOL> '<STR_LIT>' : settings_mod . SITE_ID , <EOL> '<STR_LIT>' : site_obj , <EOL> '<STR_LIT>' : list ( settings_mod . TEMPLATE_DIRS ) . index ( dir ) , <EOL> } ) <EOL> return render_to_response ( '<STR_LIT>' , { <EOL> '<STR_LIT:name>' : template , <EOL> '<STR_LIT>' : templates , <EOL> } , context_instance = RequestContext ( request ) ) <EOL> template_detail = staff_member_required ( template_detail ) <EOL> def missing_docutils_page ( request ) : <EOL> """<STR_LIT>""" <EOL> return render_to_response ( '<STR_LIT>' ) <EOL> def load_all_installed_template_libraries ( ) : <EOL> for e in templatetags . __path__ : <EOL> libraries = [ os . path . splitext ( p ) [ <NUM_LIT:0> ] for p in os . listdir ( e ) if p . endswith ( '<STR_LIT>' ) and p [ <NUM_LIT:0> ] . isalpha ( ) ] <EOL> for library_name in libraries : <EOL> try : <EOL> lib = template . get_library ( "<STR_LIT>" % library_name . split ( '<STR_LIT:.>' ) [ - <NUM_LIT:1> ] ) <EOL> except template . InvalidTemplateLibrary : <EOL> pass <EOL> def get_return_data_type ( func_name ) : <EOL> """<STR_LIT>""" <EOL> if func_name . startswith ( '<STR_LIT>' ) : <EOL> if func_name . endswith ( '<STR_LIT>' ) : <EOL> return '<STR_LIT>' <EOL> elif func_name . endswith ( '<STR_LIT>' ) : <EOL> return '<STR_LIT>' <EOL> return '<STR_LIT>' <EOL> DATA_TYPE_MAPPING = { <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> } <EOL> def get_readable_field_data_type ( field ) : <EOL> return DATA_TYPE_MAPPING [ field . get_internal_type ( ) ] % field . __dict__ <EOL> def extract_views_from_urlpatterns ( urlpatterns , base = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> views = [ ] <EOL> for p in urlpatterns : <EOL> if hasattr ( p , '<STR_LIT>' ) : <EOL> try : <EOL> views . append ( ( p . _get_callback ( ) , base + p . regex . pattern ) ) <EOL> except ViewDoesNotExist : <EOL> continue <EOL> elif hasattr ( p , '<STR_LIT>' ) : <EOL> try : <EOL> patterns = p . url_patterns <EOL> except ImportError : <EOL> continue <EOL> views . extend ( extract_views_from_urlpatterns ( patterns , base + p . regex . pattern ) ) <EOL> else : <EOL> raise TypeError , _ ( "<STR_LIT>" ) % p <EOL> return views <EOL> named_group_matcher = re . compile ( r'<STR_LIT>' ) <EOL> non_named_group_matcher = re . compile ( r'<STR_LIT>' ) <EOL> def simplify_regex ( pattern ) : <EOL> """<STR_LIT>""" <EOL> pattern = named_group_matcher . sub ( lambda m : m . group ( <NUM_LIT:1> ) , pattern ) <EOL> pattern = non_named_group_matcher . sub ( "<STR_LIT>" , pattern ) <EOL> pattern = pattern . replace ( '<STR_LIT>' , '<STR_LIT>' ) . replace ( '<STR_LIT:$>' , '<STR_LIT>' ) . replace ( '<STR_LIT:?>' , '<STR_LIT>' ) . replace ( '<STR_LIT>' , '<STR_LIT:/>' ) . replace ( '<STR_LIT:\\>' , '<STR_LIT>' ) <EOL> if not pattern . startswith ( '<STR_LIT:/>' ) : <EOL> pattern = '<STR_LIT:/>' + pattern <EOL> return pattern </s>
|
<s> from django . utils . translation import ngettext <EOL> from django . utils . translation import gettext_lazy as _ <EOL> from django import template <EOL> import re <EOL> register = template . Library ( ) <EOL> def ordinal ( value ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> value = int ( value ) <EOL> except ValueError : <EOL> return value <EOL> t = ( _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) ) <EOL> if value % <NUM_LIT:100> in ( <NUM_LIT:11> , <NUM_LIT:12> , <NUM_LIT> ) : <EOL> return "<STR_LIT>" % ( value , t [ <NUM_LIT:0> ] ) <EOL> return '<STR_LIT>' % ( value , t [ value % <NUM_LIT:10> ] ) <EOL> register . filter ( ordinal ) <EOL> def intcomma ( value ) : <EOL> """<STR_LIT>""" <EOL> orig = str ( value ) <EOL> new = re . sub ( "<STR_LIT>" , '<STR_LIT>' , str ( value ) ) <EOL> if orig == new : <EOL> return new <EOL> else : <EOL> return intcomma ( new ) <EOL> register . filter ( intcomma ) <EOL> def intword ( value ) : <EOL> """<STR_LIT>""" <EOL> value = int ( value ) <EOL> if value < <NUM_LIT> : <EOL> return value <EOL> if value < <NUM_LIT> : <EOL> new_value = value / <NUM_LIT> <EOL> return ngettext ( '<STR_LIT>' , '<STR_LIT>' , new_value ) % { '<STR_LIT:value>' : new_value } <EOL> if value < <NUM_LIT> : <EOL> new_value = value / <NUM_LIT> <EOL> return ngettext ( '<STR_LIT>' , '<STR_LIT>' , new_value ) % { '<STR_LIT:value>' : new_value } <EOL> if value < <NUM_LIT> : <EOL> new_value = value / <NUM_LIT> <EOL> return ngettext ( '<STR_LIT>' , '<STR_LIT>' , new_value ) % { '<STR_LIT:value>' : new_value } <EOL> return value <EOL> register . filter ( intword ) <EOL> def apnumber ( value ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> value = int ( value ) <EOL> except ValueError : <EOL> return value <EOL> if not <NUM_LIT:0> < value < <NUM_LIT:10> : <EOL> return value <EOL> return ( _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) , _ ( '<STR_LIT>' ) ) [ value - <NUM_LIT:1> ] <EOL> register . filter ( apnumber ) </s>
|
<s> from django . core . handlers . base import BaseHandler <EOL> from django . core import signals <EOL> from django . dispatch import dispatcher <EOL> from django . utils import datastructures <EOL> from django import http <EOL> from pprint import pformat <EOL> import os <EOL> class ModPythonRequest ( http . HttpRequest ) : <EOL> def __init__ ( self , req ) : <EOL> self . _req = req <EOL> self . path = req . uri <EOL> def __repr__ ( self ) : <EOL> try : <EOL> get = pformat ( self . GET ) <EOL> except : <EOL> get = '<STR_LIT>' <EOL> try : <EOL> post = pformat ( self . POST ) <EOL> except : <EOL> post = '<STR_LIT>' <EOL> try : <EOL> cookies = pformat ( self . COOKIES ) <EOL> except : <EOL> cookies = '<STR_LIT>' <EOL> try : <EOL> meta = pformat ( self . META ) <EOL> except : <EOL> meta = '<STR_LIT>' <EOL> return '<STR_LIT>' % ( self . path , get , post , cookies , meta ) <EOL> def get_full_path ( self ) : <EOL> return '<STR_LIT>' % ( self . path , self . _req . args and ( '<STR_LIT:?>' + self . _req . args ) or '<STR_LIT>' ) <EOL> def is_secure ( self ) : <EOL> return self . _req . subprocess_env . has_key ( '<STR_LIT>' ) and self . _req . subprocess_env [ '<STR_LIT>' ] == '<STR_LIT>' <EOL> def _load_post_and_files ( self ) : <EOL> "<STR_LIT>" <EOL> if self . _req . headers_in . has_key ( '<STR_LIT>' ) and self . _req . headers_in [ '<STR_LIT>' ] . startswith ( '<STR_LIT>' ) : <EOL> self . _post , self . _files = http . parse_file_upload ( self . _req . headers_in , self . raw_post_data ) <EOL> else : <EOL> self . _post , self . _files = http . QueryDict ( self . raw_post_data ) , datastructures . MultiValueDict ( ) <EOL> def _get_request ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _request = datastructures . MergeDict ( self . POST , self . GET ) <EOL> return self . _request <EOL> def _get_get ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _get = http . QueryDict ( self . _req . args ) <EOL> return self . _get <EOL> def _set_get ( self , get ) : <EOL> self . _get = get <EOL> def _get_post ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _load_post_and_files ( ) <EOL> return self . _post <EOL> def _set_post ( self , post ) : <EOL> self . _post = post <EOL> def _get_cookies ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _cookies = http . parse_cookie ( self . _req . headers_in . get ( '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> return self . _cookies <EOL> def _set_cookies ( self , cookies ) : <EOL> self . _cookies = cookies <EOL> def _get_files ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _load_post_and_files ( ) <EOL> return self . _files <EOL> def _get_meta ( self ) : <EOL> "<STR_LIT>" <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _meta = { <EOL> '<STR_LIT>' : self . _req . ap_auth_type , <EOL> '<STR_LIT>' : self . _req . clength , <EOL> '<STR_LIT>' : self . _req . content_type , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : self . _req . path_info , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : self . _req . args , <EOL> '<STR_LIT>' : self . _req . connection . remote_ip , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : self . _req . connection . remote_logname , <EOL> '<STR_LIT>' : self . _req . user , <EOL> '<STR_LIT>' : self . _req . method , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : self . _req . server . server_hostname , <EOL> '<STR_LIT>' : self . _req . server . port , <EOL> '<STR_LIT>' : self . _req . protocol , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> for key , value in self . _req . headers_in . items ( ) : <EOL> key = '<STR_LIT>' + key . upper ( ) . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) <EOL> self . _meta [ key ] = value <EOL> return self . _meta <EOL> def _get_raw_post_data ( self ) : <EOL> try : <EOL> return self . _raw_post_data <EOL> except AttributeError : <EOL> self . _raw_post_data = self . _req . read ( ) <EOL> return self . _raw_post_data <EOL> def _get_method ( self ) : <EOL> return self . META [ '<STR_LIT>' ] . upper ( ) <EOL> GET = property ( _get_get , _set_get ) <EOL> POST = property ( _get_post , _set_post ) <EOL> COOKIES = property ( _get_cookies , _set_cookies ) <EOL> FILES = property ( _get_files ) <EOL> META = property ( _get_meta ) <EOL> REQUEST = property ( _get_request ) <EOL> raw_post_data = property ( _get_raw_post_data ) <EOL> method = property ( _get_method ) <EOL> class ModPythonHandler ( BaseHandler ) : <EOL> def __call__ ( self , req ) : <EOL> os . environ . update ( req . subprocess_env ) <EOL> from django . conf import settings <EOL> if self . _request_middleware is None : <EOL> self . load_middleware ( ) <EOL> dispatcher . send ( signal = signals . request_started ) <EOL> try : <EOL> request = ModPythonRequest ( req ) <EOL> response = self . get_response ( request ) <EOL> for middleware_method in self . _response_middleware : <EOL> response = middleware_method ( request , response ) <EOL> finally : <EOL> dispatcher . send ( signal = signals . request_finished ) <EOL> req . content_type = response [ '<STR_LIT:Content-Type>' ] <EOL> for key , value in response . headers . items ( ) : <EOL> if key != '<STR_LIT:Content-Type>' : <EOL> req . headers_out [ key ] = value <EOL> for c in response . cookies . values ( ) : <EOL> req . headers_out . add ( '<STR_LIT>' , c . output ( header = '<STR_LIT>' ) ) <EOL> req . status = response . status_code <EOL> try : <EOL> for chunk in response : <EOL> req . write ( chunk ) <EOL> finally : <EOL> response . close ( ) <EOL> return <NUM_LIT:0> <EOL> def handler ( req ) : <EOL> return ModPythonHandler ( ) ( req ) </s>
|
<s> from django . db . backends . dummy . base import complain <EOL> get_table_list = complain <EOL> get_table_description = complain <EOL> get_relations = complain <EOL> get_indexes = complain <EOL> DATA_TYPES_REVERSE = { } </s>
|
<s> from django . db . models import signals <EOL> from django . dispatch import dispatcher <EOL> from django . conf import settings <EOL> from django . core import validators <EOL> from django import oldforms <EOL> from django import newforms as forms <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . utils . functional import curry <EOL> from django . utils . itercompat import tee <EOL> from django . utils . text import capfirst <EOL> from django . utils . translation import gettext , gettext_lazy <EOL> import datetime , os , time <EOL> class NOT_PROVIDED : <EOL> pass <EOL> HORIZONTAL , VERTICAL = <NUM_LIT:1> , <NUM_LIT:2> <EOL> BLANK_CHOICE_DASH = [ ( "<STR_LIT>" , "<STR_LIT>" ) ] <EOL> BLANK_CHOICE_NONE = [ ( "<STR_LIT>" , "<STR_LIT:None>" ) ] <EOL> prep_for_like_query = lambda x : str ( x ) . replace ( "<STR_LIT:\\>" , "<STR_LIT>" ) . replace ( "<STR_LIT:%>" , "<STR_LIT>" ) . replace ( "<STR_LIT:_>" , "<STR_LIT>" ) <EOL> get_ul_class = lambda x : '<STR_LIT>' % ( ( x == HORIZONTAL ) and '<STR_LIT>' or '<STR_LIT>' ) <EOL> class FieldDoesNotExist ( Exception ) : <EOL> pass <EOL> def manipulator_validator_unique ( f , opts , self , field_data , all_data ) : <EOL> "<STR_LIT>" <EOL> lookup_type = f . get_validator_unique_lookup_type ( ) <EOL> try : <EOL> old_obj = self . manager . get ( ** { lookup_type : field_data } ) <EOL> except ObjectDoesNotExist : <EOL> return <EOL> if getattr ( self , '<STR_LIT>' , None ) and self . original_object . _get_pk_val ( ) == old_obj . _get_pk_val ( ) : <EOL> return <EOL> raise validators . ValidationError , gettext ( "<STR_LIT>" ) % { '<STR_LIT>' : capfirst ( opts . verbose_name ) , '<STR_LIT>' : f . verbose_name } <EOL> class Field ( object ) : <EOL> empty_strings_allowed = True <EOL> creation_counter = <NUM_LIT:0> <EOL> def __init__ ( self , verbose_name = None , name = None , primary_key = False , <EOL> maxlength = None , unique = False , blank = False , null = False , db_index = False , <EOL> core = False , rel = None , default = NOT_PROVIDED , editable = True , serialize = True , <EOL> prepopulate_from = None , unique_for_date = None , unique_for_month = None , <EOL> unique_for_year = None , validator_list = None , choices = None , radio_admin = None , <EOL> help_text = '<STR_LIT>' , db_column = None ) : <EOL> self . name = name <EOL> self . verbose_name = verbose_name <EOL> self . primary_key = primary_key <EOL> self . maxlength , self . unique = maxlength , unique <EOL> self . blank , self . null = blank , null <EOL> self . core , self . rel , self . default = core , rel , default <EOL> self . editable = editable <EOL> self . serialize = serialize <EOL> self . validator_list = validator_list or [ ] <EOL> self . prepopulate_from = prepopulate_from <EOL> self . unique_for_date , self . unique_for_month = unique_for_date , unique_for_month <EOL> self . unique_for_year = unique_for_year <EOL> self . _choices = choices or [ ] <EOL> self . radio_admin = radio_admin <EOL> self . help_text = help_text <EOL> self . db_column = db_column <EOL> self . db_index = db_index <EOL> self . creation_counter = Field . creation_counter <EOL> Field . creation_counter += <NUM_LIT:1> <EOL> def __cmp__ ( self , other ) : <EOL> return cmp ( self . creation_counter , other . creation_counter ) <EOL> def to_python ( self , value ) : <EOL> """<STR_LIT>""" <EOL> return value <EOL> def validate_full ( self , field_data , all_data ) : <EOL> """<STR_LIT>""" <EOL> if not self . blank and not field_data : <EOL> return [ gettext_lazy ( '<STR_LIT>' ) ] <EOL> try : <EOL> self . validate ( field_data , all_data ) <EOL> except validators . ValidationError , e : <EOL> return e . messages <EOL> return [ ] <EOL> def validate ( self , field_data , all_data ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def set_attributes_from_name ( self , name ) : <EOL> self . name = name <EOL> self . attname , self . column = self . get_attname_column ( ) <EOL> self . verbose_name = self . verbose_name or ( name and name . replace ( '<STR_LIT:_>' , '<STR_LIT:U+0020>' ) ) <EOL> def contribute_to_class ( self , cls , name ) : <EOL> self . set_attributes_from_name ( name ) <EOL> cls . _meta . add_field ( self ) <EOL> if self . choices : <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_display , field = self ) ) <EOL> def get_attname ( self ) : <EOL> return self . name <EOL> def get_attname_column ( self ) : <EOL> attname = self . get_attname ( ) <EOL> column = self . db_column or attname <EOL> return attname , column <EOL> def get_cache_name ( self ) : <EOL> return '<STR_LIT>' % self . name <EOL> def get_internal_type ( self ) : <EOL> return self . __class__ . __name__ <EOL> def pre_save ( self , model_instance , add ) : <EOL> "<STR_LIT>" <EOL> return getattr ( model_instance , self . attname ) <EOL> def get_db_prep_save ( self , value ) : <EOL> "<STR_LIT>" <EOL> return value <EOL> def get_db_prep_lookup ( self , lookup_type , value ) : <EOL> "<STR_LIT>" <EOL> if lookup_type in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return [ value ] <EOL> elif lookup_type in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return value <EOL> elif lookup_type in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return [ "<STR_LIT>" % prep_for_like_query ( value ) ] <EOL> elif lookup_type == '<STR_LIT>' : <EOL> return [ prep_for_like_query ( value ) ] <EOL> elif lookup_type in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return [ "<STR_LIT>" % prep_for_like_query ( value ) ] <EOL> elif lookup_type in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return [ "<STR_LIT>" % prep_for_like_query ( value ) ] <EOL> elif lookup_type == '<STR_LIT>' : <EOL> return [ ] <EOL> elif lookup_type == '<STR_LIT>' : <EOL> try : <EOL> value = int ( value ) <EOL> except ValueError : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> return [ '<STR_LIT>' % value , '<STR_LIT>' % value ] <EOL> raise TypeError ( "<STR_LIT>" % lookup_type ) <EOL> def has_default ( self ) : <EOL> "<STR_LIT>" <EOL> return self . default is not NOT_PROVIDED <EOL> def get_default ( self ) : <EOL> "<STR_LIT>" <EOL> if self . default is not NOT_PROVIDED : <EOL> if callable ( self . default ) : <EOL> return self . default ( ) <EOL> return self . default <EOL> if not self . empty_strings_allowed or self . null : <EOL> return None <EOL> return "<STR_LIT>" <EOL> def get_manipulator_field_names ( self , name_prefix ) : <EOL> """<STR_LIT>""" <EOL> return [ name_prefix + self . name ] <EOL> def prepare_field_objs_and_params ( self , manipulator , name_prefix ) : <EOL> params = { '<STR_LIT>' : self . validator_list [ : ] } <EOL> if self . maxlength and not self . choices : <EOL> params [ '<STR_LIT>' ] = self . maxlength <EOL> if self . choices : <EOL> if self . radio_admin : <EOL> field_objs = [ oldforms . RadioSelectField ] <EOL> params [ '<STR_LIT>' ] = get_ul_class ( self . radio_admin ) <EOL> else : <EOL> field_objs = [ oldforms . SelectField ] <EOL> params [ '<STR_LIT>' ] = self . get_choices_default ( ) <EOL> else : <EOL> field_objs = self . get_manipulator_field_objs ( ) <EOL> return ( field_objs , params ) <EOL> def get_manipulator_fields ( self , opts , manipulator , change , name_prefix = '<STR_LIT>' , rel = False , follow = True ) : <EOL> """<STR_LIT>""" <EOL> field_objs , params = self . prepare_field_objs_and_params ( manipulator , name_prefix ) <EOL> for field_name_list in opts . unique_together : <EOL> if field_name_list [ <NUM_LIT:0> ] == self . name : <EOL> params [ '<STR_LIT>' ] . append ( getattr ( manipulator , '<STR_LIT>' % '<STR_LIT:_>' . join ( field_name_list ) ) ) <EOL> if self . unique_for_date : <EOL> params [ '<STR_LIT>' ] . append ( getattr ( manipulator , '<STR_LIT>' % ( self . name , self . unique_for_date ) ) ) <EOL> if self . unique_for_month : <EOL> params [ '<STR_LIT>' ] . append ( getattr ( manipulator , '<STR_LIT>' % ( self . name , self . unique_for_month ) ) ) <EOL> if self . unique_for_year : <EOL> params [ '<STR_LIT>' ] . append ( getattr ( manipulator , '<STR_LIT>' % ( self . name , self . unique_for_year ) ) ) <EOL> if self . unique or ( self . primary_key and not rel ) : <EOL> params [ '<STR_LIT>' ] . append ( curry ( manipulator_validator_unique , self , opts , manipulator ) ) <EOL> params [ '<STR_LIT>' ] = not self . blank and not self . primary_key and not rel <EOL> if isinstance ( self , BooleanField ) : <EOL> del params [ '<STR_LIT>' ] <EOL> if rel and not self . blank and not isinstance ( self , AutoField ) and not isinstance ( self , FileField ) : <EOL> core_field_names = [ ] <EOL> for f in opts . fields : <EOL> if f . core and f != self : <EOL> core_field_names . extend ( f . get_manipulator_field_names ( name_prefix ) ) <EOL> if core_field_names : <EOL> params [ '<STR_LIT>' ] . append ( validators . RequiredIfOtherFieldsGiven ( core_field_names , gettext_lazy ( "<STR_LIT>" ) ) ) <EOL> field_names = self . get_manipulator_field_names ( name_prefix ) <EOL> return [ man ( field_name = field_names [ i ] , ** params ) for i , man in enumerate ( field_objs ) ] <EOL> def get_validator_unique_lookup_type ( self ) : <EOL> return '<STR_LIT>' % self . name <EOL> def get_manipulator_new_data ( self , new_data , rel = False ) : <EOL> """<STR_LIT>""" <EOL> if rel : <EOL> return new_data . get ( self . name , [ self . get_default ( ) ] ) [ <NUM_LIT:0> ] <EOL> val = new_data . get ( self . name , self . get_default ( ) ) <EOL> if not self . empty_strings_allowed and val == '<STR_LIT>' and self . null : <EOL> val = None <EOL> return val <EOL> def get_choices ( self , include_blank = True , blank_choice = BLANK_CHOICE_DASH ) : <EOL> "<STR_LIT>" <EOL> first_choice = include_blank and blank_choice or [ ] <EOL> if self . choices : <EOL> return first_choice + list ( self . choices ) <EOL> rel_model = self . rel . to <EOL> if hasattr ( self . rel , '<STR_LIT>' ) : <EOL> lst = [ ( getattr ( x , self . rel . get_related_field ( ) . attname ) , str ( x ) ) for x in rel_model . _default_manager . complex_filter ( self . rel . limit_choices_to ) ] <EOL> else : <EOL> lst = [ ( x . _get_pk_val ( ) , str ( x ) ) for x in rel_model . _default_manager . complex_filter ( self . rel . limit_choices_to ) ] <EOL> return first_choice + lst <EOL> def get_choices_default ( self ) : <EOL> if self . radio_admin : <EOL> return self . get_choices ( include_blank = self . blank , blank_choice = BLANK_CHOICE_NONE ) <EOL> else : <EOL> return self . get_choices ( ) <EOL> def _get_val_from_obj ( self , obj ) : <EOL> if obj : <EOL> return getattr ( obj , self . attname ) <EOL> else : <EOL> return self . get_default ( ) <EOL> def flatten_data ( self , follow , obj = None ) : <EOL> """<STR_LIT>""" <EOL> return { self . attname : self . _get_val_from_obj ( obj ) } <EOL> def get_follow ( self , override = None ) : <EOL> if override != None : <EOL> return override <EOL> else : <EOL> return self . editable <EOL> def bind ( self , fieldmapping , original , bound_field_class ) : <EOL> return bound_field_class ( self , fieldmapping , original ) <EOL> def _get_choices ( self ) : <EOL> if hasattr ( self . _choices , '<STR_LIT>' ) : <EOL> choices , self . _choices = tee ( self . _choices ) <EOL> return choices <EOL> else : <EOL> return self . _choices <EOL> choices = property ( _get_choices ) <EOL> def formfield ( self , ** kwargs ) : <EOL> "<STR_LIT>" <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . CharField ( ** defaults ) <EOL> def value_from_object ( self , obj ) : <EOL> "<STR_LIT>" <EOL> return getattr ( obj , self . attname ) <EOL> class AutoField ( Field ) : <EOL> empty_strings_allowed = False <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> assert kwargs . get ( '<STR_LIT:primary_key>' , False ) is True , "<STR_LIT>" % self . __class__ . __name__ <EOL> kwargs [ '<STR_LIT:blank>' ] = True <EOL> Field . __init__ ( self , * args , ** kwargs ) <EOL> def to_python ( self , value ) : <EOL> if value is None : <EOL> return value <EOL> try : <EOL> return int ( value ) <EOL> except ( TypeError , ValueError ) : <EOL> raise validators . ValidationError , gettext ( "<STR_LIT>" ) <EOL> def get_manipulator_fields ( self , opts , manipulator , change , name_prefix = '<STR_LIT>' , rel = False , follow = True ) : <EOL> if not rel : <EOL> return [ ] <EOL> return Field . get_manipulator_fields ( self , opts , manipulator , change , name_prefix , rel , follow ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . HiddenField ] <EOL> def get_manipulator_new_data ( self , new_data , rel = False ) : <EOL> if not rel : <EOL> return None <EOL> return Field . get_manipulator_new_data ( self , new_data , rel ) <EOL> def contribute_to_class ( self , cls , name ) : <EOL> assert not cls . _meta . has_auto_field , "<STR_LIT>" <EOL> super ( AutoField , self ) . contribute_to_class ( cls , name ) <EOL> cls . _meta . has_auto_field = True <EOL> def formfield ( self , ** kwargs ) : <EOL> return None <EOL> class BooleanField ( Field ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT:blank>' ] = True <EOL> Field . __init__ ( self , * args , ** kwargs ) <EOL> def to_python ( self , value ) : <EOL> if value in ( True , False ) : return value <EOL> if value in ( '<STR_LIT:t>' , '<STR_LIT:True>' , '<STR_LIT:1>' ) : return True <EOL> if value in ( '<STR_LIT:f>' , '<STR_LIT:False>' , '<STR_LIT:0>' ) : return False <EOL> raise validators . ValidationError , gettext ( "<STR_LIT>" ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . CheckboxField ] <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . BooleanField ( ** defaults ) <EOL> class CharField ( Field ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . TextField ] <EOL> def to_python ( self , value ) : <EOL> if isinstance ( value , basestring ) : <EOL> return value <EOL> if value is None : <EOL> if self . null : <EOL> return value <EOL> else : <EOL> raise validators . ValidationError , gettext_lazy ( "<STR_LIT>" ) <EOL> return str ( value ) <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT:max_length>' : self . maxlength , '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . CharField ( ** defaults ) <EOL> class CommaSeparatedIntegerField ( CharField ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . CommaSeparatedIntegerField ] <EOL> class DateField ( Field ) : <EOL> empty_strings_allowed = False <EOL> def __init__ ( self , verbose_name = None , name = None , auto_now = False , auto_now_add = False , ** kwargs ) : <EOL> self . auto_now , self . auto_now_add = auto_now , auto_now_add <EOL> if auto_now or auto_now_add : <EOL> kwargs [ '<STR_LIT>' ] = False <EOL> kwargs [ '<STR_LIT:blank>' ] = True <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def to_python ( self , value ) : <EOL> if value is None : <EOL> return value <EOL> if isinstance ( value , datetime . datetime ) : <EOL> return value . date ( ) <EOL> if isinstance ( value , datetime . date ) : <EOL> return value <EOL> validators . isValidANSIDate ( value , None ) <EOL> try : <EOL> return datetime . date ( * time . strptime ( value , '<STR_LIT>' ) [ : <NUM_LIT:3> ] ) <EOL> except ValueError : <EOL> raise validators . ValidationError , gettext ( '<STR_LIT>' ) <EOL> def get_db_prep_lookup ( self , lookup_type , value ) : <EOL> if lookup_type == '<STR_LIT>' : <EOL> value = [ str ( v ) for v in value ] <EOL> elif lookup_type in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) and hasattr ( value , '<STR_LIT>' ) : <EOL> value = value . strftime ( '<STR_LIT>' ) <EOL> else : <EOL> value = str ( value ) <EOL> return Field . get_db_prep_lookup ( self , lookup_type , value ) <EOL> def pre_save ( self , model_instance , add ) : <EOL> if self . auto_now or ( self . auto_now_add and add ) : <EOL> value = datetime . datetime . now ( ) <EOL> setattr ( model_instance , self . attname , value ) <EOL> return value <EOL> else : <EOL> return super ( DateField , self ) . pre_save ( model_instance , add ) <EOL> def contribute_to_class ( self , cls , name ) : <EOL> super ( DateField , self ) . contribute_to_class ( cls , name ) <EOL> if not self . null : <EOL> setattr ( cls , '<STR_LIT>' % self . name , <EOL> curry ( cls . _get_next_or_previous_by_FIELD , field = self , is_next = True ) ) <EOL> setattr ( cls , '<STR_LIT>' % self . name , <EOL> curry ( cls . _get_next_or_previous_by_FIELD , field = self , is_next = False ) ) <EOL> def get_follow ( self , override = None ) : <EOL> if override != None : <EOL> return override <EOL> else : <EOL> return self . editable or self . auto_now or self . auto_now_add <EOL> def get_db_prep_save ( self , value ) : <EOL> if value is not None : <EOL> value = value . strftime ( '<STR_LIT>' ) <EOL> return Field . get_db_prep_save ( self , value ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . DateField ] <EOL> def flatten_data ( self , follow , obj = None ) : <EOL> val = self . _get_val_from_obj ( obj ) <EOL> return { self . attname : ( val is not None and val . strftime ( "<STR_LIT>" ) or '<STR_LIT>' ) } <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . DateField ( ** defaults ) <EOL> class DateTimeField ( DateField ) : <EOL> def to_python ( self , value ) : <EOL> if value is None : <EOL> return value <EOL> if isinstance ( value , datetime . datetime ) : <EOL> return value <EOL> if isinstance ( value , datetime . date ) : <EOL> return datetime . datetime ( value . year , value . month , value . day ) <EOL> try : <EOL> return datetime . datetime ( * time . strptime ( value , '<STR_LIT>' ) [ : <NUM_LIT:6> ] ) <EOL> except ValueError : <EOL> try : <EOL> return datetime . datetime ( * time . strptime ( value , '<STR_LIT>' ) [ : <NUM_LIT:5> ] ) <EOL> except ValueError : <EOL> try : <EOL> return datetime . datetime ( * time . strptime ( value , '<STR_LIT>' ) [ : <NUM_LIT:3> ] ) <EOL> except ValueError : <EOL> raise validators . ValidationError , gettext ( '<STR_LIT>' ) <EOL> def get_db_prep_save ( self , value ) : <EOL> if value is not None : <EOL> if settings . DATABASE_ENGINE == '<STR_LIT>' and hasattr ( value , '<STR_LIT>' ) : <EOL> value = value . replace ( microsecond = <NUM_LIT:0> ) <EOL> value = str ( value ) <EOL> return Field . get_db_prep_save ( self , value ) <EOL> def get_db_prep_lookup ( self , lookup_type , value ) : <EOL> if lookup_type == '<STR_LIT>' : <EOL> value = [ str ( v ) for v in value ] <EOL> else : <EOL> value = str ( value ) <EOL> return Field . get_db_prep_lookup ( self , lookup_type , value ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . DateField , oldforms . TimeField ] <EOL> def get_manipulator_field_names ( self , name_prefix ) : <EOL> return [ name_prefix + self . name + '<STR_LIT>' , name_prefix + self . name + '<STR_LIT>' ] <EOL> def get_manipulator_new_data ( self , new_data , rel = False ) : <EOL> date_field , time_field = self . get_manipulator_field_names ( '<STR_LIT>' ) <EOL> if rel : <EOL> d = new_data . get ( date_field , [ None ] ) [ <NUM_LIT:0> ] <EOL> t = new_data . get ( time_field , [ None ] ) [ <NUM_LIT:0> ] <EOL> else : <EOL> d = new_data . get ( date_field , None ) <EOL> t = new_data . get ( time_field , None ) <EOL> if d is not None and t is not None : <EOL> return datetime . datetime . combine ( d , t ) <EOL> return self . get_default ( ) <EOL> def flatten_data ( self , follow , obj = None ) : <EOL> val = self . _get_val_from_obj ( obj ) <EOL> date_field , time_field = self . get_manipulator_field_names ( '<STR_LIT>' ) <EOL> return { date_field : ( val is not None and val . strftime ( "<STR_LIT>" ) or '<STR_LIT>' ) , <EOL> time_field : ( val is not None and val . strftime ( "<STR_LIT>" ) or '<STR_LIT>' ) } <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . DateTimeField ( ** defaults ) <EOL> class EmailField ( CharField ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = <NUM_LIT> <EOL> CharField . __init__ ( self , * args , ** kwargs ) <EOL> def get_internal_type ( self ) : <EOL> return "<STR_LIT>" <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . EmailField ] <EOL> def validate ( self , field_data , all_data ) : <EOL> validators . isValidEmail ( field_data , all_data ) <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . EmailField ( ** defaults ) <EOL> class FileField ( Field ) : <EOL> def __init__ ( self , verbose_name = None , name = None , upload_to = '<STR_LIT>' , ** kwargs ) : <EOL> self . upload_to = upload_to <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_manipulator_fields ( self , opts , manipulator , change , name_prefix = '<STR_LIT>' , rel = False , follow = True ) : <EOL> field_list = Field . get_manipulator_fields ( self , opts , manipulator , change , name_prefix , rel , follow ) <EOL> if not self . blank : <EOL> if rel : <EOL> class RequiredFileField ( object ) : <EOL> def __init__ ( self , other_field_names , other_file_field_name ) : <EOL> self . other_field_names = other_field_names <EOL> self . other_file_field_name = other_file_field_name <EOL> self . always_test = True <EOL> def __call__ ( self , field_data , all_data ) : <EOL> if not all_data . get ( self . other_file_field_name , False ) : <EOL> c = validators . RequiredIfOtherFieldsGiven ( self . other_field_names , gettext_lazy ( "<STR_LIT>" ) ) <EOL> c ( field_data , all_data ) <EOL> core_field_names = [ ] <EOL> for f in opts . fields : <EOL> if f . core and f != self : <EOL> core_field_names . extend ( f . get_manipulator_field_names ( name_prefix ) ) <EOL> if core_field_names : <EOL> field_list [ <NUM_LIT:0> ] . validator_list . append ( RequiredFileField ( core_field_names , field_list [ <NUM_LIT:1> ] . field_name ) ) <EOL> else : <EOL> v = validators . RequiredIfOtherFieldNotGiven ( field_list [ <NUM_LIT:1> ] . field_name , gettext_lazy ( "<STR_LIT>" ) ) <EOL> v . always_test = True <EOL> field_list [ <NUM_LIT:0> ] . validator_list . append ( v ) <EOL> field_list [ <NUM_LIT:0> ] . is_required = field_list [ <NUM_LIT:1> ] . is_required = False <EOL> def isWithinMediaRoot ( field_data , all_data ) : <EOL> f = os . path . abspath ( os . path . join ( settings . MEDIA_ROOT , field_data ) ) <EOL> if not f . startswith ( os . path . abspath ( os . path . normpath ( settings . MEDIA_ROOT ) ) ) : <EOL> raise validators . ValidationError , _ ( "<STR_LIT>" ) <EOL> field_list [ <NUM_LIT:1> ] . validator_list . append ( isWithinMediaRoot ) <EOL> return field_list <EOL> def contribute_to_class ( self , cls , name ) : <EOL> super ( FileField , self ) . contribute_to_class ( cls , name ) <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_filename , field = self ) ) <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_url , field = self ) ) <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_size , field = self ) ) <EOL> setattr ( cls , '<STR_LIT>' % self . name , lambda instance , filename , raw_contents , save = True : instance . _save_FIELD_file ( self , filename , raw_contents , save ) ) <EOL> dispatcher . connect ( self . delete_file , signal = signals . post_delete , sender = cls ) <EOL> def delete_file ( self , instance ) : <EOL> if getattr ( instance , self . attname ) : <EOL> file_name = getattr ( instance , '<STR_LIT>' % self . name ) ( ) <EOL> if os . path . exists ( file_name ) and not instance . __class__ . _default_manager . filter ( ** { '<STR_LIT>' % self . name : getattr ( instance , self . attname ) } ) : <EOL> os . remove ( file_name ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . FileUploadField , oldforms . HiddenField ] <EOL> def get_manipulator_field_names ( self , name_prefix ) : <EOL> return [ name_prefix + self . name + '<STR_LIT>' , name_prefix + self . name ] <EOL> def save_file ( self , new_data , new_object , original_object , change , rel , save = True ) : <EOL> upload_field_name = self . get_manipulator_field_names ( '<STR_LIT>' ) [ <NUM_LIT:0> ] <EOL> if new_data . get ( upload_field_name , False ) : <EOL> func = getattr ( new_object , '<STR_LIT>' % self . name ) <EOL> if rel : <EOL> func ( new_data [ upload_field_name ] [ <NUM_LIT:0> ] [ "<STR_LIT:filename>" ] , new_data [ upload_field_name ] [ <NUM_LIT:0> ] [ "<STR_LIT:content>" ] , save ) <EOL> else : <EOL> func ( new_data [ upload_field_name ] [ "<STR_LIT:filename>" ] , new_data [ upload_field_name ] [ "<STR_LIT:content>" ] , save ) <EOL> def get_directory_name ( self ) : <EOL> return os . path . normpath ( datetime . datetime . now ( ) . strftime ( self . upload_to ) ) <EOL> def get_filename ( self , filename ) : <EOL> from django . utils . text import get_valid_filename <EOL> f = os . path . join ( self . get_directory_name ( ) , get_valid_filename ( os . path . basename ( filename ) ) ) <EOL> return os . path . normpath ( f ) <EOL> class FilePathField ( Field ) : <EOL> def __init__ ( self , verbose_name = None , name = None , path = '<STR_LIT>' , match = None , recursive = False , ** kwargs ) : <EOL> self . path , self . match , self . recursive = path , match , recursive <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ curry ( oldforms . FilePathField , path = self . path , match = self . match , recursive = self . recursive ) ] <EOL> class FloatField ( Field ) : <EOL> empty_strings_allowed = False <EOL> def __init__ ( self , verbose_name = None , name = None , max_digits = None , decimal_places = None , ** kwargs ) : <EOL> self . max_digits , self . decimal_places = max_digits , decimal_places <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ curry ( oldforms . FloatField , max_digits = self . max_digits , decimal_places = self . decimal_places ) ] <EOL> class ImageField ( FileField ) : <EOL> def __init__ ( self , verbose_name = None , name = None , width_field = None , height_field = None , ** kwargs ) : <EOL> self . width_field , self . height_field = width_field , height_field <EOL> FileField . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . ImageUploadField , oldforms . HiddenField ] <EOL> def contribute_to_class ( self , cls , name ) : <EOL> super ( ImageField , self ) . contribute_to_class ( cls , name ) <EOL> if not self . width_field : <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_width , field = self ) ) <EOL> if not self . height_field : <EOL> setattr ( cls , '<STR_LIT>' % self . name , curry ( cls . _get_FIELD_height , field = self ) ) <EOL> def save_file ( self , new_data , new_object , original_object , change , rel , save = True ) : <EOL> FileField . save_file ( self , new_data , new_object , original_object , change , rel , save ) <EOL> if change and ( self . width_field or self . height_field ) and save : <EOL> if self . width_field : <EOL> setattr ( new_object , self . width_field , getattr ( original_object , self . width_field ) ) <EOL> if self . height_field : <EOL> setattr ( new_object , self . height_field , getattr ( original_object , self . height_field ) ) <EOL> new_object . save ( ) <EOL> class IntegerField ( Field ) : <EOL> empty_strings_allowed = False <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . IntegerField ] <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . IntegerField ( ** defaults ) <EOL> class IPAddressField ( Field ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = <NUM_LIT:15> <EOL> Field . __init__ ( self , * args , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . IPAddressField ] <EOL> def validate ( self , field_data , all_data ) : <EOL> validators . isValidIPAddress4 ( field_data , None ) <EOL> class NullBooleanField ( Field ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT:null>' ] = True <EOL> Field . __init__ ( self , * args , ** kwargs ) <EOL> def to_python ( self , value ) : <EOL> if value in ( None , True , False ) : return value <EOL> if value in ( '<STR_LIT:None>' ) : return None <EOL> if value in ( '<STR_LIT:t>' , '<STR_LIT:True>' , '<STR_LIT:1>' ) : return True <EOL> if value in ( '<STR_LIT:f>' , '<STR_LIT:False>' , '<STR_LIT:0>' ) : return False <EOL> raise validators . ValidationError , gettext ( "<STR_LIT>" ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . NullBooleanField ] <EOL> class PhoneNumberField ( IntegerField ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . PhoneNumberField ] <EOL> def validate ( self , field_data , all_data ) : <EOL> validators . isValidPhone ( field_data , all_data ) <EOL> def formfield ( self , ** kwargs ) : <EOL> from django . contrib . localflavor . usa . forms import USPhoneNumberField <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return USPhoneNumberField ( ** defaults ) <EOL> class PositiveIntegerField ( IntegerField ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . PositiveIntegerField ] <EOL> class PositiveSmallIntegerField ( IntegerField ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . PositiveSmallIntegerField ] <EOL> class SlugField ( Field ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = kwargs . get ( '<STR_LIT>' , <NUM_LIT:50> ) <EOL> kwargs . setdefault ( '<STR_LIT>' , [ ] ) . append ( validators . isSlug ) <EOL> if not kwargs . has_key ( '<STR_LIT>' ) : <EOL> kwargs [ '<STR_LIT>' ] = True <EOL> Field . __init__ ( self , * args , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . TextField ] <EOL> class SmallIntegerField ( IntegerField ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . SmallIntegerField ] <EOL> class TextField ( Field ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . LargeTextField ] <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT>' : forms . Textarea , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . CharField ( ** defaults ) <EOL> class TimeField ( Field ) : <EOL> empty_strings_allowed = False <EOL> def __init__ ( self , verbose_name = None , name = None , auto_now = False , auto_now_add = False , ** kwargs ) : <EOL> self . auto_now , self . auto_now_add = auto_now , auto_now_add <EOL> if auto_now or auto_now_add : <EOL> kwargs [ '<STR_LIT>' ] = False <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_db_prep_lookup ( self , lookup_type , value ) : <EOL> if lookup_type == '<STR_LIT>' : <EOL> value = [ str ( v ) for v in value ] <EOL> else : <EOL> value = str ( value ) <EOL> return Field . get_db_prep_lookup ( self , lookup_type , value ) <EOL> def pre_save ( self , model_instance , add ) : <EOL> if self . auto_now or ( self . auto_now_add and add ) : <EOL> value = datetime . datetime . now ( ) . time ( ) <EOL> setattr ( model_instance , self . attname , value ) <EOL> return value <EOL> else : <EOL> return super ( TimeField , self ) . pre_save ( model_instance , add ) <EOL> def get_db_prep_save ( self , value ) : <EOL> if value is not None : <EOL> if settings . DATABASE_ENGINE == '<STR_LIT>' and hasattr ( value , '<STR_LIT>' ) : <EOL> value = value . replace ( microsecond = <NUM_LIT:0> ) <EOL> value = str ( value ) <EOL> return Field . get_db_prep_save ( self , value ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . TimeField ] <EOL> def flatten_data ( self , follow , obj = None ) : <EOL> val = self . _get_val_from_obj ( obj ) <EOL> return { self . attname : ( val is not None and val . strftime ( "<STR_LIT>" ) or '<STR_LIT>' ) } <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . TimeField ( ** defaults ) <EOL> class URLField ( CharField ) : <EOL> def __init__ ( self , verbose_name = None , name = None , verify_exists = True , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = kwargs . get ( '<STR_LIT>' , <NUM_LIT:200> ) <EOL> if verify_exists : <EOL> kwargs . setdefault ( '<STR_LIT>' , [ ] ) . append ( validators . isExistingURL ) <EOL> self . verify_exists = verify_exists <EOL> CharField . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . URLField ] <EOL> def get_internal_type ( self ) : <EOL> return "<STR_LIT>" <EOL> def formfield ( self , ** kwargs ) : <EOL> defaults = { '<STR_LIT>' : not self . blank , '<STR_LIT>' : self . verify_exists , '<STR_LIT:label>' : capfirst ( self . verbose_name ) , '<STR_LIT>' : self . help_text } <EOL> defaults . update ( kwargs ) <EOL> return forms . URLField ( ** defaults ) <EOL> class USStateField ( Field ) : <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ oldforms . USStateField ] <EOL> class XMLField ( TextField ) : <EOL> def __init__ ( self , verbose_name = None , name = None , schema_path = None , ** kwargs ) : <EOL> self . schema_path = schema_path <EOL> Field . __init__ ( self , verbose_name , name , ** kwargs ) <EOL> def get_internal_type ( self ) : <EOL> return "<STR_LIT>" <EOL> def get_manipulator_field_objs ( self ) : <EOL> return [ curry ( oldforms . XMLLargeTextField , schema_path = self . schema_path ) ] <EOL> class OrderingField ( IntegerField ) : <EOL> empty_strings_allowed = False <EOL> def __init__ ( self , with_respect_to , ** kwargs ) : <EOL> self . wrt = with_respect_to <EOL> kwargs [ '<STR_LIT:null>' ] = True <EOL> IntegerField . __init__ ( self , ** kwargs ) <EOL> def get_internal_type ( self ) : <EOL> return "<STR_LIT>" <EOL> def get_manipulator_fields ( self , opts , manipulator , change , name_prefix = '<STR_LIT>' , rel = False , follow = True ) : <EOL> return [ oldforms . HiddenField ( name_prefix + self . name ) ] </s>
|
<s> """<STR_LIT>""" <EOL> from django . newforms . widgets import Widget , Select <EOL> from django . utils . dates import MONTHS <EOL> import datetime <EOL> __all__ = ( '<STR_LIT>' , ) <EOL> class SelectDateWidget ( Widget ) : <EOL> """<STR_LIT>""" <EOL> month_field = '<STR_LIT>' <EOL> day_field = '<STR_LIT>' <EOL> year_field = '<STR_LIT>' <EOL> def __init__ ( self , attrs = None , years = None ) : <EOL> self . attrs = attrs or { } <EOL> if years : <EOL> self . years = years <EOL> else : <EOL> this_year = datetime . date . today ( ) . year <EOL> self . years = range ( this_year , this_year + <NUM_LIT:10> ) <EOL> def render ( self , name , value , attrs = None ) : <EOL> try : <EOL> value = datetime . date ( * map ( int , value . split ( '<STR_LIT:->' ) ) ) <EOL> year_val , month_val , day_val = value . year , value . month , value . day <EOL> except ( AttributeError , TypeError , ValueError ) : <EOL> year_val = month_val = day_val = None <EOL> output = [ ] <EOL> month_choices = MONTHS . items ( ) <EOL> month_choices . sort ( ) <EOL> select_html = Select ( choices = month_choices ) . render ( self . month_field % name , month_val ) <EOL> output . append ( select_html ) <EOL> day_choices = [ ( i , i ) for i in range ( <NUM_LIT:1> , <NUM_LIT:32> ) ] <EOL> select_html = Select ( choices = day_choices ) . render ( self . day_field % name , day_val ) <EOL> output . append ( select_html ) <EOL> year_choices = [ ( i , i ) for i in self . years ] <EOL> select_html = Select ( choices = year_choices ) . render ( self . year_field % name , year_val ) <EOL> output . append ( select_html ) <EOL> return u'<STR_LIT:\n>' . join ( output ) <EOL> def value_from_datadict ( self , data , name ) : <EOL> y , m , d = data . get ( self . year_field % name ) , data . get ( self . month_field % name ) , data . get ( self . day_field % name ) <EOL> if y and m and d : <EOL> return '<STR_LIT>' % ( y , m , d ) <EOL> return None </s>
|
<s> """<STR_LIT>""" <EOL> import datetime , md5 , re <EOL> from django . conf import settings <EOL> from django . core . cache import cache <EOL> cc_delim_re = re . compile ( r'<STR_LIT>' ) <EOL> def patch_cache_control ( response , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> def dictitem ( s ) : <EOL> t = s . split ( '<STR_LIT:=>' , <NUM_LIT:1> ) <EOL> if len ( t ) > <NUM_LIT:1> : <EOL> return ( t [ <NUM_LIT:0> ] . lower ( ) . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) , t [ <NUM_LIT:1> ] ) <EOL> else : <EOL> return ( t [ <NUM_LIT:0> ] . lower ( ) . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) , True ) <EOL> def dictvalue ( t ) : <EOL> if t [ <NUM_LIT:1> ] == True : <EOL> return t [ <NUM_LIT:0> ] <EOL> else : <EOL> return t [ <NUM_LIT:0> ] + '<STR_LIT:=>' + str ( t [ <NUM_LIT:1> ] ) <EOL> if response . has_header ( '<STR_LIT>' ) : <EOL> cc = cc_delim_re . split ( response [ '<STR_LIT>' ] ) <EOL> cc = dict ( [ dictitem ( el ) for el in cc ] ) <EOL> else : <EOL> cc = { } <EOL> for ( k , v ) in kwargs . items ( ) : <EOL> cc [ k . replace ( '<STR_LIT:_>' , '<STR_LIT:->' ) ] = v <EOL> cc = '<STR_LIT:U+002CU+0020>' . join ( [ dictvalue ( el ) for el in cc . items ( ) ] ) <EOL> response [ '<STR_LIT>' ] = cc <EOL> vary_delim_re = re . compile ( r'<STR_LIT>' ) <EOL> def patch_response_headers ( response , cache_timeout = None ) : <EOL> """<STR_LIT>""" <EOL> if cache_timeout is None : <EOL> cache_timeout = settings . CACHE_MIDDLEWARE_SECONDS <EOL> now = datetime . datetime . utcnow ( ) <EOL> if not response . has_header ( '<STR_LIT>' ) : <EOL> response [ '<STR_LIT>' ] = md5 . new ( response . content ) . hexdigest ( ) <EOL> if not response . has_header ( '<STR_LIT>' ) : <EOL> response [ '<STR_LIT>' ] = now . strftime ( '<STR_LIT>' ) <EOL> if not response . has_header ( '<STR_LIT>' ) : <EOL> expires = now + datetime . timedelta ( <NUM_LIT:0> , cache_timeout ) <EOL> response [ '<STR_LIT>' ] = expires . strftime ( '<STR_LIT>' ) <EOL> if cache_timeout < <NUM_LIT:0> : <EOL> cache_timeout = <NUM_LIT:0> <EOL> patch_cache_control ( response , max_age = cache_timeout ) <EOL> def add_never_cache_headers ( response ) : <EOL> """<STR_LIT>""" <EOL> patch_response_headers ( response , cache_timeout = - <NUM_LIT:1> ) <EOL> def patch_vary_headers ( response , newheaders ) : <EOL> """<STR_LIT>""" <EOL> vary = [ ] <EOL> if response . has_header ( '<STR_LIT>' ) : <EOL> vary = vary_delim_re . split ( response [ '<STR_LIT>' ] ) <EOL> oldheaders = dict ( [ ( el . lower ( ) , <NUM_LIT:1> ) for el in vary ] ) <EOL> for newheader in newheaders : <EOL> if not newheader . lower ( ) in oldheaders : <EOL> vary . append ( newheader ) <EOL> response [ '<STR_LIT>' ] = '<STR_LIT:U+002CU+0020>' . join ( vary ) <EOL> def _generate_cache_key ( request , headerlist , key_prefix ) : <EOL> "<STR_LIT>" <EOL> ctx = md5 . new ( ) <EOL> for header in headerlist : <EOL> value = request . META . get ( header , None ) <EOL> if value is not None : <EOL> ctx . update ( value ) <EOL> return '<STR_LIT>' % ( key_prefix , request . path , ctx . hexdigest ( ) ) <EOL> def get_cache_key ( request , key_prefix = None ) : <EOL> """<STR_LIT>""" <EOL> if key_prefix is None : <EOL> key_prefix = settings . CACHE_MIDDLEWARE_KEY_PREFIX <EOL> cache_key = '<STR_LIT>' % ( key_prefix , request . path ) <EOL> headerlist = cache . get ( cache_key , None ) <EOL> if headerlist is not None : <EOL> return _generate_cache_key ( request , headerlist , key_prefix ) <EOL> else : <EOL> return None <EOL> def learn_cache_key ( request , response , cache_timeout = None , key_prefix = None ) : <EOL> """<STR_LIT>""" <EOL> if key_prefix is None : <EOL> key_prefix = settings . CACHE_MIDDLEWARE_KEY_PREFIX <EOL> if cache_timeout is None : <EOL> cache_timeout = settings . CACHE_MIDDLEWARE_SECONDS <EOL> cache_key = '<STR_LIT>' % ( key_prefix , request . path ) <EOL> if response . has_header ( '<STR_LIT>' ) : <EOL> headerlist = [ '<STR_LIT>' + header . upper ( ) . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) for header in vary_delim_re . split ( response [ '<STR_LIT>' ] ) ] <EOL> cache . set ( cache_key , headerlist , cache_timeout ) <EOL> return _generate_cache_key ( request , headerlist , key_prefix ) <EOL> else : <EOL> cache . set ( cache_key , [ ] , cache_timeout ) <EOL> return _generate_cache_key ( request , [ ] , key_prefix ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . utils . decorators import decorator_from_middleware <EOL> from django . middleware . http import ConditionalGetMiddleware <EOL> from django . http import HttpResponseNotAllowed <EOL> conditional_page = decorator_from_middleware ( ConditionalGetMiddleware ) <EOL> def require_http_methods ( request_method_list ) : <EOL> """<STR_LIT>""" <EOL> def decorator ( func ) : <EOL> def inner ( request , * args , ** kwargs ) : <EOL> if request . method not in request_method_list : <EOL> return HttpResponseNotAllowed ( request_method_list ) <EOL> return func ( request , * args , ** kwargs ) <EOL> return inner <EOL> return decorator <EOL> require_GET = require_http_methods ( [ "<STR_LIT:GET>" ] ) <EOL> require_GET . __doc__ = "<STR_LIT>" <EOL> require_POST = require_http_methods ( [ "<STR_LIT:POST>" ] ) <EOL> require_POST . __doc__ = "<STR_LIT>" </s>
|
<s> DATE_FORMAT = r'<STR_LIT>' <EOL> TIME_FORMAT = '<STR_LIT>' <EOL> DATETIME_FORMAT = r'<STR_LIT>' <EOL> YEAR_MONTH_FORMAT = r'<STR_LIT>' <EOL> MONTH_DAY_FORMAT = r'<STR_LIT>' <EOL> SHORT_DATE_FORMAT = '<STR_LIT>' <EOL> SHORT_DATETIME_FORMAT = '<STR_LIT>' <EOL> FIRST_DAY_OF_WEEK = <NUM_LIT:1> <EOL> DATE_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ) <EOL> TIME_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ) <EOL> DATETIME_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> DECIMAL_SEPARATOR = '<STR_LIT:U+002C>' <EOL> THOUSAND_SEPARATOR = '<STR_LIT:.>' <EOL> NUMBER_GROUPING = <NUM_LIT:3> </s>
|
<s> DATE_FORMAT = '<STR_LIT>' <EOL> TIME_FORMAT = '<STR_LIT>' <EOL> DATETIME_FORMAT = '<STR_LIT>' <EOL> YEAR_MONTH_FORMAT = '<STR_LIT>' <EOL> MONTH_DAY_FORMAT = '<STR_LIT>' <EOL> SHORT_DATE_FORMAT = '<STR_LIT>' <EOL> SHORT_DATETIME_FORMAT = '<STR_LIT>' <EOL> FIRST_DAY_OF_WEEK = <NUM_LIT:1> <EOL> DATE_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> TIME_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> DATETIME_INPUT_FORMATS = ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> DECIMAL_SEPARATOR = '<STR_LIT:U+002C>' <EOL> THOUSAND_SEPARATOR = '<STR_LIT:.>' <EOL> NUMBER_GROUPING = <NUM_LIT:3> </s>
|
<s> from django import template <EOL> register = template . Library ( ) <EOL> def prepopulated_fields_js ( context ) : <EOL> """<STR_LIT>""" <EOL> prepopulated_fields = [ ] <EOL> if context [ '<STR_LIT>' ] and '<STR_LIT>' in context : <EOL> prepopulated_fields . extend ( context [ '<STR_LIT>' ] . prepopulated_fields ) <EOL> if '<STR_LIT>' in context : <EOL> for inline_admin_formset in context [ '<STR_LIT>' ] : <EOL> for inline_admin_form in inline_admin_formset : <EOL> if inline_admin_form . original is None : <EOL> prepopulated_fields . extend ( inline_admin_form . prepopulated_fields ) <EOL> context . update ( { '<STR_LIT>' : prepopulated_fields } ) <EOL> return context <EOL> prepopulated_fields_js = register . inclusion_tag ( '<STR_LIT>' , takes_context = True ) ( prepopulated_fields_js ) <EOL> def submit_row ( context ) : <EOL> """<STR_LIT>""" <EOL> opts = context [ '<STR_LIT>' ] <EOL> change = context [ '<STR_LIT>' ] <EOL> is_popup = context [ '<STR_LIT>' ] <EOL> save_as = context [ '<STR_LIT>' ] <EOL> return { <EOL> '<STR_LIT>' : ( opts . get_ordered_objects ( ) and change <EOL> and '<STR_LIT>' or '<STR_LIT>' ) , <EOL> '<STR_LIT>' : ( not is_popup and context [ '<STR_LIT>' ] <EOL> and ( change or context [ '<STR_LIT>' ] ) ) , <EOL> '<STR_LIT>' : not is_popup and change and save_as , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] and <EOL> not is_popup and ( not save_as or context [ '<STR_LIT>' ] ) , <EOL> '<STR_LIT>' : not is_popup and context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : is_popup , <EOL> '<STR_LIT>' : True <EOL> } <EOL> submit_row = register . inclusion_tag ( '<STR_LIT>' , takes_context = True ) ( submit_row ) </s>
|
<s> from django . conf import settings <EOL> from django . contrib . auth . models import User , Group , Permission , AnonymousUser <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . core . exceptions import ImproperlyConfigured <EOL> from django . test import TestCase <EOL> class BackendTest ( TestCase ) : <EOL> backend = '<STR_LIT>' <EOL> def setUp ( self ) : <EOL> self . curr_auth = settings . AUTHENTICATION_BACKENDS <EOL> settings . AUTHENTICATION_BACKENDS = ( self . backend , ) <EOL> User . objects . create_user ( '<STR_LIT:test>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> User . objects . create_superuser ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> def tearDown ( self ) : <EOL> settings . AUTHENTICATION_BACKENDS = self . curr_auth <EOL> ContentType . objects . clear_cache ( ) <EOL> def test_has_perm ( self ) : <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , False ) <EOL> user . is_staff = True <EOL> user . save ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , False ) <EOL> user . is_superuser = True <EOL> user . save ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , True ) <EOL> user . is_staff = False <EOL> user . is_superuser = False <EOL> user . save ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , False ) <EOL> user . is_staff = True <EOL> user . is_superuser = True <EOL> user . is_active = False <EOL> user . save ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , False ) <EOL> def test_custom_perms ( self ) : <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> content_type = ContentType . objects . get_for_model ( Group ) <EOL> perm = Permission . objects . create ( name = '<STR_LIT:test>' , content_type = content_type , codename = '<STR_LIT:test>' ) <EOL> user . user_permissions . add ( perm ) <EOL> user . save ( ) <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> self . assertEqual ( user . get_all_permissions ( ) == set ( [ u'<STR_LIT>' ] ) , True ) <EOL> self . assertEqual ( user . get_group_permissions ( ) , set ( [ ] ) ) <EOL> self . assertEqual ( user . has_module_perms ( '<STR_LIT>' ) , False ) <EOL> self . assertEqual ( user . has_module_perms ( '<STR_LIT>' ) , True ) <EOL> perm = Permission . objects . create ( name = '<STR_LIT>' , content_type = content_type , codename = '<STR_LIT>' ) <EOL> user . user_permissions . add ( perm ) <EOL> user . save ( ) <EOL> perm = Permission . objects . create ( name = '<STR_LIT>' , content_type = content_type , codename = '<STR_LIT>' ) <EOL> user . user_permissions . add ( perm ) <EOL> user . save ( ) <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> self . assertEqual ( user . get_all_permissions ( ) , set ( [ u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' ] ) ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT:test>' ) , False ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , True ) <EOL> self . assertEqual ( user . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] ) , True ) <EOL> perm = Permission . objects . create ( name = '<STR_LIT>' , content_type = content_type , codename = '<STR_LIT>' ) <EOL> group = Group . objects . create ( name = '<STR_LIT>' ) <EOL> group . permissions . add ( perm ) <EOL> group . save ( ) <EOL> user . groups . add ( group ) <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> exp = set ( [ u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' ] ) <EOL> self . assertEqual ( user . get_all_permissions ( ) , exp ) <EOL> self . assertEqual ( user . get_group_permissions ( ) , set ( [ u'<STR_LIT>' ] ) ) <EOL> self . assertEqual ( user . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] ) , True ) <EOL> user = AnonymousUser ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT:test>' ) , False ) <EOL> self . assertEqual ( user . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] ) , False ) <EOL> def test_has_no_object_perm ( self ) : <EOL> """<STR_LIT>""" <EOL> user = User . objects . get ( username = '<STR_LIT:test>' ) <EOL> content_type = ContentType . objects . get_for_model ( Group ) <EOL> perm = Permission . objects . create ( name = '<STR_LIT:test>' , content_type = content_type , codename = '<STR_LIT:test>' ) <EOL> user . user_permissions . add ( perm ) <EOL> user . save ( ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' , '<STR_LIT:object>' ) , False ) <EOL> self . assertEqual ( user . get_all_permissions ( '<STR_LIT:object>' ) , set ( [ ] ) ) <EOL> self . assertEqual ( user . has_perm ( '<STR_LIT>' ) , True ) <EOL> self . assertEqual ( user . get_all_permissions ( ) , set ( [ '<STR_LIT>' ] ) ) <EOL> def test_get_all_superuser_permissions ( self ) : <EOL> "<STR_LIT>" <EOL> user = User . objects . get ( username = '<STR_LIT>' ) <EOL> self . assertEqual ( len ( user . get_all_permissions ( ) ) , len ( Permission . objects . all ( ) ) ) <EOL> class TestObj ( object ) : <EOL> pass <EOL> class SimpleRowlevelBackend ( object ) : <EOL> supports_object_permissions = True <EOL> def has_perm ( self , user , perm , obj = None ) : <EOL> if not obj : <EOL> return <EOL> if isinstance ( obj , TestObj ) : <EOL> if user . username == '<STR_LIT>' : <EOL> return True <EOL> elif user . is_anonymous ( ) and perm == '<STR_LIT>' : <EOL> return True <EOL> return False <EOL> def has_module_perms ( self , user , app_label ) : <EOL> return app_label == "<STR_LIT>" <EOL> def get_all_permissions ( self , user , obj = None ) : <EOL> if not obj : <EOL> return [ ] <EOL> if not isinstance ( obj , TestObj ) : <EOL> return [ '<STR_LIT:none>' ] <EOL> if user . is_anonymous ( ) : <EOL> return [ '<STR_LIT>' ] <EOL> if user . username == '<STR_LIT>' : <EOL> return [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> else : <EOL> return [ '<STR_LIT>' ] <EOL> def get_group_permissions ( self , user , obj = None ) : <EOL> if not obj : <EOL> return <EOL> if not isinstance ( obj , TestObj ) : <EOL> return [ '<STR_LIT:none>' ] <EOL> if '<STR_LIT>' in [ group . name for group in user . groups . all ( ) ] : <EOL> return [ '<STR_LIT>' ] <EOL> else : <EOL> return [ '<STR_LIT:none>' ] <EOL> class RowlevelBackendTest ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> backend = '<STR_LIT>' <EOL> def setUp ( self ) : <EOL> self . curr_auth = settings . AUTHENTICATION_BACKENDS <EOL> settings . AUTHENTICATION_BACKENDS = tuple ( self . curr_auth ) + ( self . backend , ) <EOL> self . user1 = User . objects . create_user ( '<STR_LIT:test>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> self . user2 = User . objects . create_user ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> self . user3 = User . objects . create_user ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> def tearDown ( self ) : <EOL> settings . AUTHENTICATION_BACKENDS = self . curr_auth <EOL> ContentType . objects . clear_cache ( ) <EOL> def test_has_perm ( self ) : <EOL> self . assertEqual ( self . user1 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> self . assertEqual ( self . user2 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , True ) <EOL> self . assertEqual ( self . user2 . has_perm ( '<STR_LIT>' ) , False ) <EOL> self . assertEqual ( self . user2 . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] , TestObj ( ) ) , True ) <EOL> self . assertEqual ( self . user3 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> self . assertEqual ( self . user3 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> self . assertEqual ( self . user3 . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] , TestObj ( ) ) , False ) <EOL> def test_get_all_permissions ( self ) : <EOL> self . assertEqual ( self . user1 . get_all_permissions ( TestObj ( ) ) , set ( [ '<STR_LIT>' ] ) ) <EOL> self . assertEqual ( self . user2 . get_all_permissions ( TestObj ( ) ) , set ( [ '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> self . assertEqual ( self . user2 . get_all_permissions ( ) , set ( [ ] ) ) <EOL> def test_get_group_permissions ( self ) : <EOL> content_type = ContentType . objects . get_for_model ( Group ) <EOL> group = Group . objects . create ( name = '<STR_LIT>' ) <EOL> self . user3 . groups . add ( group ) <EOL> self . assertEqual ( self . user3 . get_group_permissions ( TestObj ( ) ) , set ( [ '<STR_LIT>' ] ) ) <EOL> class AnonymousUserBackend ( SimpleRowlevelBackend ) : <EOL> supports_anonymous_user = True <EOL> class NoAnonymousUserBackend ( SimpleRowlevelBackend ) : <EOL> supports_anonymous_user = False <EOL> class AnonymousUserBackendTest ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> backend = '<STR_LIT>' <EOL> def setUp ( self ) : <EOL> self . curr_auth = settings . AUTHENTICATION_BACKENDS <EOL> settings . AUTHENTICATION_BACKENDS = ( self . backend , ) <EOL> self . user1 = AnonymousUser ( ) <EOL> def tearDown ( self ) : <EOL> settings . AUTHENTICATION_BACKENDS = self . curr_auth <EOL> def test_has_perm ( self ) : <EOL> self . assertEqual ( self . user1 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> self . assertEqual ( self . user1 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , True ) <EOL> def test_has_perms ( self ) : <EOL> self . assertEqual ( self . user1 . has_perms ( [ '<STR_LIT>' ] , TestObj ( ) ) , True ) <EOL> self . assertEqual ( self . user1 . has_perms ( [ '<STR_LIT>' , '<STR_LIT>' ] , TestObj ( ) ) , False ) <EOL> def test_has_module_perms ( self ) : <EOL> self . assertEqual ( self . user1 . has_module_perms ( "<STR_LIT>" ) , True ) <EOL> self . assertEqual ( self . user1 . has_module_perms ( "<STR_LIT>" ) , False ) <EOL> def test_get_all_permissions ( self ) : <EOL> self . assertEqual ( self . user1 . get_all_permissions ( TestObj ( ) ) , set ( [ '<STR_LIT>' ] ) ) <EOL> class NoAnonymousUserBackendTest ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> backend = '<STR_LIT>' <EOL> def setUp ( self ) : <EOL> self . curr_auth = settings . AUTHENTICATION_BACKENDS <EOL> settings . AUTHENTICATION_BACKENDS = tuple ( self . curr_auth ) + ( self . backend , ) <EOL> self . user1 = AnonymousUser ( ) <EOL> def tearDown ( self ) : <EOL> settings . AUTHENTICATION_BACKENDS = self . curr_auth <EOL> def test_has_perm ( self ) : <EOL> self . assertEqual ( self . user1 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> self . assertEqual ( self . user1 . has_perm ( '<STR_LIT>' , TestObj ( ) ) , False ) <EOL> def test_has_perms ( self ) : <EOL> self . assertEqual ( self . user1 . has_perms ( [ '<STR_LIT>' ] , TestObj ( ) ) , False ) <EOL> def test_has_module_perms ( self ) : <EOL> self . assertEqual ( self . user1 . has_module_perms ( "<STR_LIT>" ) , False ) <EOL> self . assertEqual ( self . user1 . has_module_perms ( "<STR_LIT>" ) , False ) <EOL> def test_get_all_permissions ( self ) : <EOL> self . assertEqual ( self . user1 . get_all_permissions ( TestObj ( ) ) , set ( ) ) <EOL> class NoBackendsTest ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . old_AUTHENTICATION_BACKENDS = settings . AUTHENTICATION_BACKENDS <EOL> settings . AUTHENTICATION_BACKENDS = [ ] <EOL> self . user = User . objects . create_user ( '<STR_LIT:test>' , '<STR_LIT>' , '<STR_LIT:test>' ) <EOL> def tearDown ( self ) : <EOL> settings . AUTHENTICATION_BACKENDS = self . old_AUTHENTICATION_BACKENDS <EOL> def test_raises_exception ( self ) : <EOL> self . assertRaises ( ImproperlyConfigured , self . user . has_perm , ( '<STR_LIT>' , TestObj ( ) , ) ) </s>
|
<s> from django import db <EOL> from django . conf import settings <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . contrib . sites . models import Site <EOL> from django . contrib . contenttypes . views import shortcut <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . http import HttpRequest <EOL> from django . test import TestCase <EOL> class ContentTypesTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . old_DEBUG = settings . DEBUG <EOL> self . old_Site_meta_installed = Site . _meta . installed <EOL> settings . DEBUG = True <EOL> ContentType . objects . clear_cache ( ) <EOL> db . reset_queries ( ) <EOL> def tearDown ( self ) : <EOL> settings . DEBUG = self . old_DEBUG <EOL> Site . _meta . installed = self . old_Site_meta_installed <EOL> def test_lookup_cache ( self ) : <EOL> """<STR_LIT>""" <EOL> ContentType . objects . get_for_model ( ContentType ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( db . connection . queries ) ) <EOL> ct = ContentType . objects . get_for_model ( ContentType ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( db . connection . queries ) ) <EOL> ContentType . objects . get_for_id ( ct . id ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( db . connection . queries ) ) <EOL> ContentType . objects . clear_cache ( ) <EOL> ContentType . objects . get_for_model ( ContentType ) <EOL> len ( db . connection . queries ) <EOL> self . assertEqual ( <NUM_LIT:2> , len ( db . connection . queries ) ) <EOL> def test_shortcut_view ( self ) : <EOL> """<STR_LIT>""" <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> } <EOL> from django . contrib . auth . models import User <EOL> user_ct = ContentType . objects . get_for_model ( User ) <EOL> obj = User . objects . create ( username = "<STR_LIT>" ) <EOL> if Site . _meta . installed : <EOL> response = shortcut ( request , user_ct . id , obj . id ) <EOL> self . assertEqual ( "<STR_LIT>" , response . _headers . get ( "<STR_LIT:location>" ) [ <NUM_LIT:1> ] ) <EOL> Site . _meta . installed = False <EOL> response = shortcut ( request , user_ct . id , obj . id ) <EOL> self . assertEqual ( "<STR_LIT>" , response . _headers . get ( "<STR_LIT:location>" ) [ <NUM_LIT:1> ] ) </s>
|
<s> from django . conf import settings <EOL> from django . contrib . gis . gdal import OGRException <EOL> from django . contrib . gis . geos import GEOSGeometry , GEOSException <EOL> from django . forms . widgets import Textarea <EOL> from django . template import loader , Context <EOL> from django . utils import translation <EOL> geo_context = Context ( { '<STR_LIT>' : settings . ADMIN_MEDIA_PREFIX , <EOL> '<STR_LIT>' : translation . get_language_bidi ( ) , <EOL> } ) <EOL> class OpenLayersWidget ( Textarea ) : <EOL> """<STR_LIT>""" <EOL> def render ( self , name , value , attrs = None ) : <EOL> if attrs : self . params . update ( attrs ) <EOL> self . params [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> if isinstance ( value , basestring ) : <EOL> try : <EOL> value = GEOSGeometry ( value ) <EOL> except ( GEOSException , ValueError ) : <EOL> value = None <EOL> if value and value . geom_type . upper ( ) != self . geom_type : <EOL> value = None <EOL> self . params [ '<STR_LIT>' ] = self . map_options ( ) <EOL> self . params [ '<STR_LIT:name>' ] = name <EOL> js_safe_name = self . params [ '<STR_LIT:name>' ] . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) <EOL> self . params [ '<STR_LIT>' ] = '<STR_LIT>' % js_safe_name <EOL> if value : <EOL> srid = self . params [ '<STR_LIT>' ] <EOL> if value . srid != srid : <EOL> try : <EOL> ogr = value . ogr <EOL> ogr . transform ( srid ) <EOL> wkt = ogr . wkt <EOL> except OGRException : <EOL> wkt = '<STR_LIT>' <EOL> else : <EOL> wkt = value . wkt <EOL> self . params [ '<STR_LIT>' ] = wkt <EOL> return loader . render_to_string ( self . template , self . params , <EOL> context_instance = geo_context ) <EOL> def map_options ( self ) : <EOL> "<STR_LIT>" <EOL> def ol_bounds ( extent ) : <EOL> return '<STR_LIT>' % str ( extent ) <EOL> def ol_projection ( srid ) : <EOL> return '<STR_LIT>' % srid <EOL> map_types = [ ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , str ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , float ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , int ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , int ) , <EOL> ( '<STR_LIT>' , '<STR_LIT>' , int ) , <EOL> ] <EOL> map_options = { } <EOL> for param_name , js_name , option_type in map_types : <EOL> if self . params . get ( param_name , False ) : <EOL> if option_type == '<STR_LIT>' : <EOL> value = ol_projection ( self . params [ param_name ] ) <EOL> elif option_type == '<STR_LIT>' : <EOL> value = ol_bounds ( self . params [ param_name ] ) <EOL> elif option_type in ( float , int ) : <EOL> value = self . params [ param_name ] <EOL> elif option_type in ( str , ) : <EOL> value = '<STR_LIT>' % self . params [ param_name ] <EOL> else : <EOL> raise TypeError <EOL> map_options [ js_name ] = value <EOL> return map_options </s>
|
<s> """<STR_LIT>""" <EOL> def gqn ( val ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( val , basestring ) : <EOL> if isinstance ( val , unicode ) : val = val . encode ( '<STR_LIT:ascii>' ) <EOL> return "<STR_LIT>" % val <EOL> else : <EOL> return str ( val ) <EOL> class SpatialOperation ( object ) : <EOL> """<STR_LIT>""" <EOL> sql_template = '<STR_LIT>' <EOL> def __init__ ( self , function = '<STR_LIT>' , operator = '<STR_LIT>' , result = '<STR_LIT>' , ** kwargs ) : <EOL> self . function = function <EOL> self . operator = operator <EOL> self . result = result <EOL> self . extra = kwargs <EOL> def as_sql ( self , geo_col , geometry = '<STR_LIT:%s>' ) : <EOL> return self . sql_template % self . params ( geo_col , geometry ) <EOL> def params ( self , geo_col , geometry ) : <EOL> params = { '<STR_LIT>' : self . function , <EOL> '<STR_LIT>' : geo_col , <EOL> '<STR_LIT>' : geometry , <EOL> '<STR_LIT>' : self . operator , <EOL> '<STR_LIT:result>' : self . result , <EOL> } <EOL> params . update ( self . extra ) <EOL> return params <EOL> class SpatialFunction ( SpatialOperation ) : <EOL> """<STR_LIT>""" <EOL> sql_template = '<STR_LIT>' <EOL> def __init__ ( self , func , result = '<STR_LIT>' , operator = '<STR_LIT>' , ** kwargs ) : <EOL> default = { '<STR_LIT>' : func , <EOL> '<STR_LIT>' : operator , <EOL> '<STR_LIT:result>' : result <EOL> } <EOL> kwargs . update ( default ) <EOL> super ( SpatialFunction , self ) . __init__ ( ** kwargs ) </s>
|
<s> """<STR_LIT>""" <EOL> from ctypes import c_char_p , c_double , c_int , c_long , c_void_p , POINTER <EOL> from django . contrib . gis . gdal . envelope import OGREnvelope <EOL> from django . contrib . gis . gdal . libgdal import lgdal <EOL> from django . contrib . gis . gdal . prototypes . generation import const_string_output , double_output , geom_output , int_output , srs_output , void_output , voidptr_output <EOL> c_int_p = POINTER ( c_int ) <EOL> register_all = void_output ( lgdal . OGRRegisterAll , [ ] , errcheck = False ) <EOL> cleanup_all = void_output ( lgdal . OGRCleanupAll , [ ] , errcheck = False ) <EOL> get_driver = voidptr_output ( lgdal . OGRGetDriver , [ c_int ] ) <EOL> get_driver_by_name = voidptr_output ( lgdal . OGRGetDriverByName , [ c_char_p ] ) <EOL> get_driver_count = int_output ( lgdal . OGRGetDriverCount , [ ] ) <EOL> get_driver_name = const_string_output ( lgdal . OGR_Dr_GetName , [ c_void_p ] ) <EOL> open_ds = voidptr_output ( lgdal . OGROpen , [ c_char_p , c_int , POINTER ( c_void_p ) ] ) <EOL> destroy_ds = void_output ( lgdal . OGR_DS_Destroy , [ c_void_p ] , errcheck = False ) <EOL> release_ds = void_output ( lgdal . OGRReleaseDataSource , [ c_void_p ] ) <EOL> get_ds_name = const_string_output ( lgdal . OGR_DS_GetName , [ c_void_p ] ) <EOL> get_layer = voidptr_output ( lgdal . OGR_DS_GetLayer , [ c_void_p , c_int ] ) <EOL> get_layer_by_name = voidptr_output ( lgdal . OGR_DS_GetLayerByName , [ c_void_p , c_char_p ] ) <EOL> get_layer_count = int_output ( lgdal . OGR_DS_GetLayerCount , [ c_void_p ] ) <EOL> get_extent = void_output ( lgdal . OGR_L_GetExtent , [ c_void_p , POINTER ( OGREnvelope ) , c_int ] ) <EOL> get_feature = voidptr_output ( lgdal . OGR_L_GetFeature , [ c_void_p , c_long ] ) <EOL> get_feature_count = int_output ( lgdal . OGR_L_GetFeatureCount , [ c_void_p , c_int ] ) <EOL> get_layer_defn = voidptr_output ( lgdal . OGR_L_GetLayerDefn , [ c_void_p ] ) <EOL> get_layer_srs = srs_output ( lgdal . OGR_L_GetSpatialRef , [ c_void_p ] ) <EOL> get_next_feature = voidptr_output ( lgdal . OGR_L_GetNextFeature , [ c_void_p ] ) <EOL> reset_reading = void_output ( lgdal . OGR_L_ResetReading , [ c_void_p ] , errcheck = False ) <EOL> test_capability = int_output ( lgdal . OGR_L_TestCapability , [ c_void_p , c_char_p ] ) <EOL> get_spatial_filter = geom_output ( lgdal . OGR_L_GetSpatialFilter , [ c_void_p ] ) <EOL> set_spatial_filter = void_output ( lgdal . OGR_L_SetSpatialFilter , [ c_void_p , c_void_p ] , errcheck = False ) <EOL> set_spatial_filter_rect = void_output ( lgdal . OGR_L_SetSpatialFilterRect , [ c_void_p , c_double , c_double , c_double , c_double ] , errcheck = False ) <EOL> get_fd_geom_type = int_output ( lgdal . OGR_FD_GetGeomType , [ c_void_p ] ) <EOL> get_fd_name = const_string_output ( lgdal . OGR_FD_GetName , [ c_void_p ] ) <EOL> get_feat_name = const_string_output ( lgdal . OGR_FD_GetName , [ c_void_p ] ) <EOL> get_field_count = int_output ( lgdal . OGR_FD_GetFieldCount , [ c_void_p ] ) <EOL> get_field_defn = voidptr_output ( lgdal . OGR_FD_GetFieldDefn , [ c_void_p , c_int ] ) <EOL> clone_feature = voidptr_output ( lgdal . OGR_F_Clone , [ c_void_p ] ) <EOL> destroy_feature = void_output ( lgdal . OGR_F_Destroy , [ c_void_p ] , errcheck = False ) <EOL> feature_equal = int_output ( lgdal . OGR_F_Equal , [ c_void_p , c_void_p ] ) <EOL> get_feat_geom_ref = geom_output ( lgdal . OGR_F_GetGeometryRef , [ c_void_p ] ) <EOL> get_feat_field_count = int_output ( lgdal . OGR_F_GetFieldCount , [ c_void_p ] ) <EOL> get_feat_field_defn = voidptr_output ( lgdal . OGR_F_GetFieldDefnRef , [ c_void_p , c_int ] ) <EOL> get_fid = int_output ( lgdal . OGR_F_GetFID , [ c_void_p ] ) <EOL> get_field_as_datetime = int_output ( lgdal . OGR_F_GetFieldAsDateTime , [ c_void_p , c_int , c_int_p , c_int_p , c_int_p , c_int_p , c_int_p , c_int_p ] ) <EOL> get_field_as_double = double_output ( lgdal . OGR_F_GetFieldAsDouble , [ c_void_p , c_int ] ) <EOL> get_field_as_integer = int_output ( lgdal . OGR_F_GetFieldAsInteger , [ c_void_p , c_int ] ) <EOL> get_field_as_string = const_string_output ( lgdal . OGR_F_GetFieldAsString , [ c_void_p , c_int ] ) <EOL> get_field_index = int_output ( lgdal . OGR_F_GetFieldIndex , [ c_void_p , c_char_p ] ) <EOL> get_field_name = const_string_output ( lgdal . OGR_Fld_GetNameRef , [ c_void_p ] ) <EOL> get_field_precision = int_output ( lgdal . OGR_Fld_GetPrecision , [ c_void_p ] ) <EOL> get_field_type = int_output ( lgdal . OGR_Fld_GetType , [ c_void_p ] ) <EOL> get_field_type_name = const_string_output ( lgdal . OGR_GetFieldTypeName , [ c_int ] ) <EOL> get_field_width = int_output ( lgdal . OGR_Fld_GetWidth , [ c_void_p ] ) </s>
|
<s> from ctypes import c_uint , byref <EOL> from django . contrib . gis . geos . error import GEOSIndexError <EOL> from django . contrib . gis . geos . geometry import GEOSGeometry <EOL> from django . contrib . gis . geos . libgeos import get_pointer_arr , GEOM_PTR <EOL> from django . contrib . gis . geos . linestring import LinearRing <EOL> from django . contrib . gis . geos import prototypes as capi <EOL> class Polygon ( GEOSGeometry ) : <EOL> _minlength = <NUM_LIT:1> <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> if not args : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> ext_ring = args [ <NUM_LIT:0> ] <EOL> init_holes = args [ <NUM_LIT:1> : ] <EOL> n_holes = len ( init_holes ) <EOL> if n_holes == <NUM_LIT:1> and isinstance ( init_holes [ <NUM_LIT:0> ] , ( tuple , list ) ) : <EOL> if len ( init_holes [ <NUM_LIT:0> ] ) == <NUM_LIT:0> : <EOL> init_holes = ( ) <EOL> n_holes = <NUM_LIT:0> <EOL> elif isinstance ( init_holes [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , LinearRing ) : <EOL> init_holes = init_holes [ <NUM_LIT:0> ] <EOL> n_holes = len ( init_holes ) <EOL> polygon = self . _create_polygon ( n_holes + <NUM_LIT:1> , ( ext_ring , ) + init_holes ) <EOL> super ( Polygon , self ) . __init__ ( polygon , ** kwargs ) <EOL> def __iter__ ( self ) : <EOL> "<STR_LIT>" <EOL> for i in xrange ( len ( self ) ) : <EOL> yield self [ i ] <EOL> def __len__ ( self ) : <EOL> "<STR_LIT>" <EOL> return self . num_interior_rings + <NUM_LIT:1> <EOL> @ classmethod <EOL> def from_bbox ( cls , bbox ) : <EOL> "<STR_LIT>" <EOL> x0 , y0 , x1 , y1 = bbox <EOL> return GEOSGeometry ( '<STR_LIT>' % ( <EOL> x0 , y0 , x0 , y1 , x1 , y1 , x1 , y0 , x0 , y0 ) ) <EOL> def _create_polygon ( self , length , items ) : <EOL> rings = [ ] <EOL> for r in items : <EOL> if isinstance ( r , GEOM_PTR ) : <EOL> rings . append ( r ) <EOL> else : <EOL> rings . append ( self . _construct_ring ( r ) ) <EOL> shell = self . _clone ( rings . pop ( <NUM_LIT:0> ) ) <EOL> n_holes = length - <NUM_LIT:1> <EOL> if n_holes : <EOL> holes = get_pointer_arr ( n_holes ) <EOL> for i , r in enumerate ( rings ) : <EOL> holes [ i ] = self . _clone ( r ) <EOL> holes_param = byref ( holes ) <EOL> else : <EOL> holes_param = None <EOL> return capi . create_polygon ( shell , holes_param , c_uint ( n_holes ) ) <EOL> def _clone ( self , g ) : <EOL> if isinstance ( g , GEOM_PTR ) : <EOL> return capi . geom_clone ( g ) <EOL> else : <EOL> return capi . geom_clone ( g . ptr ) <EOL> def _construct_ring ( self , param , msg = '<STR_LIT>' ) : <EOL> "<STR_LIT>" <EOL> if isinstance ( param , LinearRing ) : return param <EOL> try : <EOL> ring = LinearRing ( param ) <EOL> return ring <EOL> except TypeError : <EOL> raise TypeError ( msg ) <EOL> def _set_list ( self , length , items ) : <EOL> prev_ptr = self . ptr <EOL> srid = self . srid <EOL> self . ptr = self . _create_polygon ( length , items ) <EOL> if srid : self . srid = srid <EOL> capi . destroy_geom ( prev_ptr ) <EOL> def _get_single_internal ( self , index ) : <EOL> """<STR_LIT>""" <EOL> if index == <NUM_LIT:0> : <EOL> return capi . get_extring ( self . ptr ) <EOL> else : <EOL> return capi . get_intring ( self . ptr , index - <NUM_LIT:1> ) <EOL> def _get_single_external ( self , index ) : <EOL> return GEOSGeometry ( capi . geom_clone ( self . _get_single_internal ( index ) ) , srid = self . srid ) <EOL> _set_single = GEOSGeometry . _set_single_rebuild <EOL> _assign_extended_slice = GEOSGeometry . _assign_extended_slice_rebuild <EOL> @ property <EOL> def num_interior_rings ( self ) : <EOL> "<STR_LIT>" <EOL> return capi . get_nrings ( self . ptr ) <EOL> def _get_ext_ring ( self ) : <EOL> "<STR_LIT>" <EOL> return self [ <NUM_LIT:0> ] <EOL> def _set_ext_ring ( self , ring ) : <EOL> "<STR_LIT>" <EOL> self [ <NUM_LIT:0> ] = ring <EOL> exterior_ring = property ( _get_ext_ring , _set_ext_ring ) <EOL> shell = exterior_ring <EOL> @ property <EOL> def tuple ( self ) : <EOL> "<STR_LIT>" <EOL> return tuple ( [ self [ i ] . tuple for i in xrange ( len ( self ) ) ] ) <EOL> coords = tuple <EOL> @ property <EOL> def kml ( self ) : <EOL> "<STR_LIT>" <EOL> inner_kml = '<STR_LIT>' . join ( [ "<STR_LIT>" % self [ i + <NUM_LIT:1> ] . kml <EOL> for i in xrange ( self . num_interior_rings ) ] ) <EOL> return "<STR_LIT>" % ( self [ <NUM_LIT:0> ] . kml , inner_kml ) </s>
|
<s> from django . contrib . gis . sitemaps . georss import GeoRSSSitemap <EOL> from django . contrib . gis . sitemaps . kml import KMLSitemap , KMZSitemap </s>
|
<s> """<STR_LIT>""" <EOL> from django . contrib . gis . gdal import HAS_GDAL <EOL> if HAS_GDAL : <EOL> from django . contrib . gis . utils . ogrinfo import ogrinfo , sample <EOL> from django . contrib . gis . utils . ogrinspect import mapping , ogrinspect <EOL> from django . contrib . gis . utils . srs import add_postgis_srs , add_srs_entry <EOL> try : <EOL> from django . contrib . gis . utils . layermapping import LayerMapping , LayerMapError <EOL> except : <EOL> pass <EOL> try : <EOL> from django . contrib . gis . utils . geoip import GeoIP , GeoIPException <EOL> HAS_GEOIP = True <EOL> except : <EOL> HAS_GEOIP = False <EOL> from django . contrib . gis . utils . wkt import precision_wkt </s>
|
<s> """<STR_LIT>""" <EOL> import re <EOL> from django . forms import ValidationError <EOL> from django . forms . fields import Select , RegexField <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from django . core . validators import EMPTY_VALUES <EOL> class PLProvinceSelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> from pl_voivodeships import VOIVODESHIP_CHOICES <EOL> super ( PLProvinceSelect , self ) . __init__ ( attrs , choices = VOIVODESHIP_CHOICES ) <EOL> class PLCountySelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> from pl_administrativeunits import ADMINISTRATIVE_UNIT_CHOICES <EOL> super ( PLCountySelect , self ) . __init__ ( attrs , choices = ADMINISTRATIVE_UNIT_CHOICES ) <EOL> class PLPESELField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( PLPESELField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> super ( PLPESELField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> if not self . has_valid_checksum ( value ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return u'<STR_LIT:%s>' % value <EOL> def has_valid_checksum ( self , number ) : <EOL> """<STR_LIT>""" <EOL> multiple_table = ( <NUM_LIT:1> , <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT:9> , <NUM_LIT:1> , <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT:9> , <NUM_LIT:1> , <NUM_LIT:3> , <NUM_LIT:1> ) <EOL> result = <NUM_LIT:0> <EOL> for i in range ( len ( number ) ) : <EOL> result += int ( number [ i ] ) * multiple_table [ i ] <EOL> return result % <NUM_LIT:10> == <NUM_LIT:0> <EOL> class PLNIPField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( PLNIPField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> super ( PLNIPField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> value = re . sub ( "<STR_LIT>" , "<STR_LIT>" , value ) <EOL> if not self . has_valid_checksum ( value ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return u'<STR_LIT:%s>' % value <EOL> def has_valid_checksum ( self , number ) : <EOL> """<STR_LIT>""" <EOL> multiple_table = ( <NUM_LIT:6> , <NUM_LIT:5> , <NUM_LIT:7> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> , <NUM_LIT:7> ) <EOL> result = <NUM_LIT:0> <EOL> for i in range ( len ( number ) - <NUM_LIT:1> ) : <EOL> result += int ( number [ i ] ) * multiple_table [ i ] <EOL> result %= <NUM_LIT:11> <EOL> if result == int ( number [ - <NUM_LIT:1> ] ) : <EOL> return True <EOL> else : <EOL> return False <EOL> class PLREGONField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( PLREGONField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> super ( PLREGONField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> if not self . has_valid_checksum ( value ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return u'<STR_LIT:%s>' % value <EOL> def has_valid_checksum ( self , number ) : <EOL> """<STR_LIT>""" <EOL> weights = ( <EOL> ( <NUM_LIT:8> , <NUM_LIT:9> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> , <NUM_LIT:7> , - <NUM_LIT:1> ) , <EOL> ( <NUM_LIT:2> , <NUM_LIT:4> , <NUM_LIT:8> , <NUM_LIT:5> , <NUM_LIT:0> , <NUM_LIT:9> , <NUM_LIT:7> , <NUM_LIT:3> , <NUM_LIT:6> , <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:4> , <NUM_LIT:8> , - <NUM_LIT:1> ) , <EOL> ( <NUM_LIT:8> , <NUM_LIT:9> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> , <NUM_LIT:7> , - <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) , <EOL> ) <EOL> weights = [ table for table in weights if len ( table ) == len ( number ) ] <EOL> for table in weights : <EOL> checksum = sum ( [ int ( n ) * w for n , w in zip ( number , table ) ] ) <EOL> if checksum % <NUM_LIT:11> % <NUM_LIT:10> : <EOL> return False <EOL> return bool ( weights ) <EOL> class PLPostalCodeField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( PLPostalCodeField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) </s>
|
<s> from django . conf import settings <EOL> from django . contrib . messages . storage import default_storage <EOL> class MessageMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def process_request ( self , request ) : <EOL> request . _messages = default_storage ( request ) <EOL> def process_response ( self , request , response ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( request , '<STR_LIT>' ) : <EOL> unstored_messages = request . _messages . update ( response ) <EOL> if unstored_messages and settings . DEBUG : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> return response </s>
|
<s> r"""<STR_LIT>""" <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import doctest <EOL> doctest . testmod ( ) </s>
|
<s> import os <EOL> try : <EOL> from cStringIO import StringIO <EOL> except ImportError : <EOL> from StringIO import StringIO <EOL> from django . utils . encoding import smart_str , smart_unicode <EOL> from django . core . files . utils import FileProxyMixin <EOL> class File ( FileProxyMixin ) : <EOL> DEFAULT_CHUNK_SIZE = <NUM_LIT:64> * <NUM_LIT:2> ** <NUM_LIT:10> <EOL> def __init__ ( self , file , name = None ) : <EOL> self . file = file <EOL> if name is None : <EOL> name = getattr ( file , '<STR_LIT:name>' , None ) <EOL> self . name = name <EOL> self . mode = getattr ( file , '<STR_LIT>' , None ) <EOL> def __str__ ( self ) : <EOL> return smart_str ( self . name or '<STR_LIT>' ) <EOL> def __unicode__ ( self ) : <EOL> return smart_unicode ( self . name or u'<STR_LIT>' ) <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . __class__ . __name__ , self or "<STR_LIT:None>" ) <EOL> def __nonzero__ ( self ) : <EOL> return bool ( self . name ) <EOL> def __len__ ( self ) : <EOL> return self . size <EOL> def _get_size ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> if hasattr ( self . file , '<STR_LIT:size>' ) : <EOL> self . _size = self . file . size <EOL> elif os . path . exists ( self . file . name ) : <EOL> self . _size = os . path . getsize ( self . file . name ) <EOL> else : <EOL> raise AttributeError ( "<STR_LIT>" ) <EOL> return self . _size <EOL> def _set_size ( self , size ) : <EOL> self . _size = size <EOL> size = property ( _get_size , _set_size ) <EOL> def _get_closed ( self ) : <EOL> return not self . file or self . file . closed <EOL> closed = property ( _get_closed ) <EOL> def chunks ( self , chunk_size = None ) : <EOL> """<STR_LIT>""" <EOL> if not chunk_size : <EOL> chunk_size = self . DEFAULT_CHUNK_SIZE <EOL> if hasattr ( self , '<STR_LIT>' ) : <EOL> self . seek ( <NUM_LIT:0> ) <EOL> counter = self . size <EOL> while counter > <NUM_LIT:0> : <EOL> yield self . read ( chunk_size ) <EOL> counter -= chunk_size <EOL> def multiple_chunks ( self , chunk_size = None ) : <EOL> """<STR_LIT>""" <EOL> if not chunk_size : <EOL> chunk_size = self . DEFAULT_CHUNK_SIZE <EOL> return self . size > chunk_size <EOL> def __iter__ ( self ) : <EOL> buffer_ = None <EOL> for chunk in self . chunks ( ) : <EOL> chunk_buffer = StringIO ( chunk ) <EOL> for line in chunk_buffer : <EOL> if buffer_ : <EOL> line = buffer_ + line <EOL> buffer_ = None <EOL> if line [ - <NUM_LIT:1> ] in ( '<STR_LIT:\n>' , '<STR_LIT:\r>' ) : <EOL> yield line <EOL> else : <EOL> buffer_ = line <EOL> if buffer_ is not None : <EOL> yield buffer_ <EOL> def open ( self , mode = None ) : <EOL> if not self . closed : <EOL> self . seek ( <NUM_LIT:0> ) <EOL> elif self . name and os . path . exists ( self . name ) : <EOL> self . file = open ( self . name , mode or self . mode ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> def close ( self ) : <EOL> self . file . close ( ) <EOL> class ContentFile ( File ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , content ) : <EOL> content = content or '<STR_LIT>' <EOL> super ( ContentFile , self ) . __init__ ( StringIO ( content ) ) <EOL> self . size = len ( content ) <EOL> def __str__ ( self ) : <EOL> return '<STR_LIT>' <EOL> def __nonzero__ ( self ) : <EOL> return True <EOL> def open ( self , mode = None ) : <EOL> self . seek ( <NUM_LIT:0> ) <EOL> def close ( self ) : <EOL> pass </s>
|
<s> import keyword <EOL> from optparse import make_option <EOL> from django . core . management . base import NoArgsCommand , CommandError <EOL> from django . db import connections , DEFAULT_DB_ALIAS <EOL> class Command ( NoArgsCommand ) : <EOL> help = "<STR_LIT>" <EOL> option_list = NoArgsCommand . option_list + ( <EOL> make_option ( '<STR_LIT>' , action = '<STR_LIT:store>' , dest = '<STR_LIT>' , <EOL> default = DEFAULT_DB_ALIAS , help = '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> ) <EOL> requires_model_validation = False <EOL> db_module = '<STR_LIT>' <EOL> def handle_noargs ( self , ** options ) : <EOL> try : <EOL> for line in self . handle_inspection ( options ) : <EOL> self . stdout . write ( "<STR_LIT>" % line ) <EOL> except NotImplementedError : <EOL> raise CommandError ( "<STR_LIT>" ) <EOL> def handle_inspection ( self , options ) : <EOL> connection = connections [ options . get ( '<STR_LIT>' , DEFAULT_DB_ALIAS ) ] <EOL> table2model = lambda table_name : table_name . title ( ) . replace ( '<STR_LIT:_>' , '<STR_LIT>' ) . replace ( '<STR_LIT:U+0020>' , '<STR_LIT>' ) . replace ( '<STR_LIT:->' , '<STR_LIT>' ) <EOL> cursor = connection . cursor ( ) <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT:#>" <EOL> yield "<STR_LIT>" <EOL> yield "<STR_LIT>" <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' % self . db_module <EOL> yield '<STR_LIT>' <EOL> for table_name in connection . introspection . get_table_list ( cursor ) : <EOL> yield '<STR_LIT>' % table2model ( table_name ) <EOL> try : <EOL> relations = connection . introspection . get_relations ( cursor , table_name ) <EOL> except NotImplementedError : <EOL> relations = { } <EOL> try : <EOL> indexes = connection . introspection . get_indexes ( cursor , table_name ) <EOL> except NotImplementedError : <EOL> indexes = { } <EOL> for i , row in enumerate ( connection . introspection . get_table_description ( cursor , table_name ) ) : <EOL> column_name = row [ <NUM_LIT:0> ] <EOL> att_name = column_name . lower ( ) <EOL> comment_notes = [ ] <EOL> extra_params = { } <EOL> if '<STR_LIT:U+0020>' in att_name or '<STR_LIT:->' in att_name or keyword . iskeyword ( att_name ) or column_name != att_name : <EOL> extra_params [ '<STR_LIT>' ] = column_name <EOL> if '<STR_LIT:U+0020>' in att_name : <EOL> att_name = att_name . replace ( '<STR_LIT:U+0020>' , '<STR_LIT:_>' ) <EOL> comment_notes . append ( '<STR_LIT>' ) <EOL> if '<STR_LIT:->' in att_name : <EOL> att_name = att_name . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) <EOL> comment_notes . append ( '<STR_LIT>' ) <EOL> if column_name != att_name : <EOL> comment_notes . append ( '<STR_LIT>' ) <EOL> if i in relations : <EOL> rel_to = relations [ i ] [ <NUM_LIT:1> ] == table_name and "<STR_LIT>" or table2model ( relations [ i ] [ <NUM_LIT:1> ] ) <EOL> field_type = '<STR_LIT>' % rel_to <EOL> if att_name . endswith ( '<STR_LIT>' ) : <EOL> att_name = att_name [ : - <NUM_LIT:3> ] <EOL> else : <EOL> extra_params [ '<STR_LIT>' ] = column_name <EOL> else : <EOL> field_type , field_params , field_notes = self . get_field_type ( connection , table_name , row ) <EOL> extra_params . update ( field_params ) <EOL> comment_notes . extend ( field_notes ) <EOL> if column_name in indexes : <EOL> if indexes [ column_name ] [ '<STR_LIT:primary_key>' ] : <EOL> extra_params [ '<STR_LIT:primary_key>' ] = True <EOL> elif indexes [ column_name ] [ '<STR_LIT>' ] : <EOL> extra_params [ '<STR_LIT>' ] = True <EOL> field_type += '<STR_LIT:(>' <EOL> if keyword . iskeyword ( att_name ) : <EOL> att_name += '<STR_LIT>' <EOL> comment_notes . append ( '<STR_LIT>' ) <EOL> if att_name == '<STR_LIT:id>' and field_type == '<STR_LIT>' and extra_params == { '<STR_LIT:primary_key>' : True } : <EOL> continue <EOL> if row [ <NUM_LIT:6> ] : <EOL> extra_params [ '<STR_LIT:blank>' ] = True <EOL> if not field_type in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> extra_params [ '<STR_LIT:null>' ] = True <EOL> field_desc = '<STR_LIT>' % ( att_name , field_type ) <EOL> if extra_params : <EOL> if not field_desc . endswith ( '<STR_LIT:(>' ) : <EOL> field_desc += '<STR_LIT:U+002CU+0020>' <EOL> field_desc += '<STR_LIT:U+002CU+0020>' . join ( [ '<STR_LIT>' % ( k , v ) for k , v in extra_params . items ( ) ] ) <EOL> field_desc += '<STR_LIT:)>' <EOL> if comment_notes : <EOL> field_desc += '<STR_LIT>' + '<STR_LIT:U+0020>' . join ( comment_notes ) <EOL> yield '<STR_LIT>' % field_desc <EOL> for meta_line in self . get_meta ( table_name ) : <EOL> yield meta_line <EOL> def get_field_type ( self , connection , table_name , row ) : <EOL> """<STR_LIT>""" <EOL> field_params = { } <EOL> field_notes = [ ] <EOL> try : <EOL> field_type = connection . introspection . get_field_type ( row [ <NUM_LIT:1> ] , row ) <EOL> except KeyError : <EOL> field_type = '<STR_LIT>' <EOL> field_notes . append ( '<STR_LIT>' ) <EOL> if type ( field_type ) is tuple : <EOL> field_type , new_params = field_type <EOL> field_params . update ( new_params ) <EOL> if field_type == '<STR_LIT>' and row [ <NUM_LIT:3> ] : <EOL> field_params [ '<STR_LIT:max_length>' ] = row [ <NUM_LIT:3> ] <EOL> if field_type == '<STR_LIT>' : <EOL> field_params [ '<STR_LIT>' ] = row [ <NUM_LIT:4> ] <EOL> field_params [ '<STR_LIT>' ] = row [ <NUM_LIT:5> ] <EOL> return field_type , field_params , field_notes <EOL> def get_meta ( self , table_name ) : <EOL> """<STR_LIT>""" <EOL> return [ '<STR_LIT>' , <EOL> '<STR_LIT>' % table_name , <EOL> '<STR_LIT>' ] </s>
|
<s> """<STR_LIT>""" <EOL> from StringIO import StringIO <EOL> import decimal <EOL> import yaml <EOL> from django . db import models <EOL> from django . core . serializers . python import Serializer as PythonSerializer <EOL> from django . core . serializers . python import Deserializer as PythonDeserializer <EOL> class DjangoSafeDumper ( yaml . SafeDumper ) : <EOL> def represent_decimal ( self , data ) : <EOL> return self . represent_scalar ( '<STR_LIT>' , str ( data ) ) <EOL> DjangoSafeDumper . add_representer ( decimal . Decimal , DjangoSafeDumper . represent_decimal ) <EOL> class Serializer ( PythonSerializer ) : <EOL> """<STR_LIT>""" <EOL> internal_use_only = False <EOL> def handle_field ( self , obj , field ) : <EOL> if isinstance ( field , models . TimeField ) and getattr ( obj , field . name ) is not None : <EOL> self . _current [ field . name ] = str ( getattr ( obj , field . name ) ) <EOL> else : <EOL> super ( Serializer , self ) . handle_field ( obj , field ) <EOL> def end_serialization ( self ) : <EOL> yaml . dump ( self . objects , self . stream , Dumper = DjangoSafeDumper , ** self . options ) <EOL> def getvalue ( self ) : <EOL> return self . stream . getvalue ( ) <EOL> def Deserializer ( stream_or_string , ** options ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( stream_or_string , basestring ) : <EOL> stream = StringIO ( stream_or_string ) <EOL> else : <EOL> stream = stream_or_string <EOL> for obj in PythonDeserializer ( yaml . load ( stream ) , ** options ) : <EOL> yield obj </s>
|
<s> """<STR_LIT>""" <EOL> import re <EOL> VERSION_RE = re . compile ( r'<STR_LIT>' ) <EOL> def _parse_version ( text ) : <EOL> "<STR_LIT>" <EOL> major , major2 , minor = VERSION_RE . search ( text ) . groups ( ) <EOL> try : <EOL> return int ( major ) , int ( major2 ) , int ( minor ) <EOL> except ( ValueError , TypeError ) : <EOL> return int ( major ) , int ( major2 ) , None <EOL> def get_version ( cursor ) : <EOL> """<STR_LIT>""" <EOL> cursor . execute ( "<STR_LIT>" ) <EOL> return _parse_version ( cursor . fetchone ( ) [ <NUM_LIT:0> ] ) </s>
|
<s> import re <EOL> QUERY_TERMS = dict ( [ ( x , None ) for x in ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) ] ) <EOL> GET_ITERATOR_CHUNK_SIZE = <NUM_LIT:100> <EOL> LOOKUP_SEP = '<STR_LIT>' <EOL> TABLE_NAME = <NUM_LIT:0> <EOL> RHS_ALIAS = <NUM_LIT:1> <EOL> JOIN_TYPE = <NUM_LIT:2> <EOL> LHS_ALIAS = <NUM_LIT:3> <EOL> LHS_JOIN_COL = <NUM_LIT:4> <EOL> RHS_JOIN_COL = <NUM_LIT:5> <EOL> NULLABLE = <NUM_LIT:6> <EOL> MULTI = '<STR_LIT>' <EOL> SINGLE = '<STR_LIT>' <EOL> ORDER_PATTERN = re . compile ( r'<STR_LIT>' ) <EOL> ORDER_DIR = { <EOL> '<STR_LIT>' : ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , '<STR_LIT>' ) } </s>
|
<s> "<STR_LIT>" <EOL> from django . utils . cache import patch_vary_headers <EOL> from django . utils import translation <EOL> class LocaleMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def process_request ( self , request ) : <EOL> language = translation . get_language_from_request ( request ) <EOL> translation . activate ( language ) <EOL> request . LANGUAGE_CODE = translation . get_language ( ) <EOL> def process_response ( self , request , response ) : <EOL> patch_vary_headers ( response , ( '<STR_LIT>' , ) ) <EOL> if '<STR_LIT>' not in response : <EOL> response [ '<STR_LIT>' ] = translation . get_language ( ) <EOL> translation . deactivate ( ) <EOL> return response </s>
|
<s> import types <EOL> import urllib <EOL> import locale <EOL> import datetime <EOL> import codecs <EOL> from decimal import Decimal <EOL> from django . utils . functional import Promise <EOL> class DjangoUnicodeDecodeError ( UnicodeDecodeError ) : <EOL> def __init__ ( self , obj , * args ) : <EOL> self . obj = obj <EOL> UnicodeDecodeError . __init__ ( self , * args ) <EOL> def __str__ ( self ) : <EOL> original = UnicodeDecodeError . __str__ ( self ) <EOL> return '<STR_LIT>' % ( original , self . obj , <EOL> type ( self . obj ) ) <EOL> class StrAndUnicode ( object ) : <EOL> """<STR_LIT>""" <EOL> def __str__ ( self ) : <EOL> return self . __unicode__ ( ) . encode ( '<STR_LIT:utf-8>' ) <EOL> def smart_unicode ( s , encoding = '<STR_LIT:utf-8>' , strings_only = False , errors = '<STR_LIT:strict>' ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( s , Promise ) : <EOL> return s <EOL> return force_unicode ( s , encoding , strings_only , errors ) <EOL> def is_protected_type ( obj ) : <EOL> """<STR_LIT>""" <EOL> return isinstance ( obj , ( <EOL> types . NoneType , <EOL> int , long , <EOL> datetime . datetime , datetime . date , datetime . time , <EOL> float , Decimal ) <EOL> ) <EOL> def force_unicode ( s , encoding = '<STR_LIT:utf-8>' , strings_only = False , errors = '<STR_LIT:strict>' ) : <EOL> """<STR_LIT>""" <EOL> if strings_only and is_protected_type ( s ) : <EOL> return s <EOL> try : <EOL> if not isinstance ( s , basestring , ) : <EOL> if hasattr ( s , '<STR_LIT>' ) : <EOL> s = unicode ( s ) <EOL> else : <EOL> try : <EOL> s = unicode ( str ( s ) , encoding , errors ) <EOL> except UnicodeEncodeError : <EOL> if not isinstance ( s , Exception ) : <EOL> raise <EOL> s = '<STR_LIT:U+0020>' . join ( [ force_unicode ( arg , encoding , strings_only , <EOL> errors ) for arg in s ] ) <EOL> elif not isinstance ( s , unicode ) : <EOL> s = s . decode ( encoding , errors ) <EOL> except UnicodeDecodeError , e : <EOL> if not isinstance ( s , Exception ) : <EOL> raise DjangoUnicodeDecodeError ( s , * e . args ) <EOL> else : <EOL> s = '<STR_LIT:U+0020>' . join ( [ force_unicode ( arg , encoding , strings_only , <EOL> errors ) for arg in s ] ) <EOL> return s <EOL> def smart_str ( s , encoding = '<STR_LIT:utf-8>' , strings_only = False , errors = '<STR_LIT:strict>' ) : <EOL> """<STR_LIT>""" <EOL> if strings_only and isinstance ( s , ( types . NoneType , int ) ) : <EOL> return s <EOL> if isinstance ( s , Promise ) : <EOL> return unicode ( s ) . encode ( encoding , errors ) <EOL> elif not isinstance ( s , basestring ) : <EOL> try : <EOL> return str ( s ) <EOL> except UnicodeEncodeError : <EOL> if isinstance ( s , Exception ) : <EOL> return '<STR_LIT:U+0020>' . join ( [ smart_str ( arg , encoding , strings_only , <EOL> errors ) for arg in s ] ) <EOL> return unicode ( s ) . encode ( encoding , errors ) <EOL> elif isinstance ( s , unicode ) : <EOL> return s . encode ( encoding , errors ) <EOL> elif s and encoding != '<STR_LIT:utf-8>' : <EOL> return s . decode ( '<STR_LIT:utf-8>' , errors ) . encode ( encoding , errors ) <EOL> else : <EOL> return s <EOL> def iri_to_uri ( iri ) : <EOL> """<STR_LIT>""" <EOL> if iri is None : <EOL> return iri <EOL> return urllib . quote ( smart_str ( iri ) , safe = "<STR_LIT>" ) <EOL> def filepath_to_uri ( path ) : <EOL> """<STR_LIT>""" <EOL> if path is None : <EOL> return path <EOL> return urllib . quote ( smart_str ( path ) . replace ( "<STR_LIT:\\>" , "<STR_LIT:/>" ) , safe = "<STR_LIT>" ) <EOL> try : <EOL> DEFAULT_LOCALE_ENCODING = locale . getdefaultlocale ( ) [ <NUM_LIT:1> ] or '<STR_LIT:ascii>' <EOL> codecs . lookup ( DEFAULT_LOCALE_ENCODING ) <EOL> except : <EOL> DEFAULT_LOCALE_ENCODING = '<STR_LIT:ascii>' </s>
|
<s> from django . template import loader , RequestContext <EOL> from django . http import Http404 , HttpResponse <EOL> from django . core . xheaders import populate_xheaders <EOL> from django . core . paginator import Paginator , InvalidPage <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> def object_list ( request , queryset , paginate_by = None , page = None , <EOL> allow_empty = True , template_name = None , template_loader = loader , <EOL> extra_context = None , context_processors = None , template_object_name = '<STR_LIT:object>' , <EOL> mimetype = None ) : <EOL> """<STR_LIT>""" <EOL> if extra_context is None : extra_context = { } <EOL> queryset = queryset . _clone ( ) <EOL> if paginate_by : <EOL> paginator = Paginator ( queryset , paginate_by , allow_empty_first_page = allow_empty ) <EOL> if not page : <EOL> page = request . GET . get ( '<STR_LIT>' , <NUM_LIT:1> ) <EOL> try : <EOL> page_number = int ( page ) <EOL> except ValueError : <EOL> if page == '<STR_LIT>' : <EOL> page_number = paginator . num_pages <EOL> else : <EOL> raise Http404 <EOL> try : <EOL> page_obj = paginator . page ( page_number ) <EOL> except InvalidPage : <EOL> raise Http404 <EOL> c = RequestContext ( request , { <EOL> '<STR_LIT>' % template_object_name : page_obj . object_list , <EOL> '<STR_LIT>' : paginator , <EOL> '<STR_LIT>' : page_obj , <EOL> '<STR_LIT>' : page_obj . has_other_pages ( ) , <EOL> '<STR_LIT>' : paginator . per_page , <EOL> '<STR_LIT>' : page_obj . has_next ( ) , <EOL> '<STR_LIT>' : page_obj . has_previous ( ) , <EOL> '<STR_LIT>' : page_obj . number , <EOL> '<STR_LIT>' : page_obj . next_page_number ( ) , <EOL> '<STR_LIT>' : page_obj . previous_page_number ( ) , <EOL> '<STR_LIT>' : page_obj . start_index ( ) , <EOL> '<STR_LIT>' : page_obj . end_index ( ) , <EOL> '<STR_LIT>' : paginator . num_pages , <EOL> '<STR_LIT>' : paginator . count , <EOL> '<STR_LIT>' : paginator . page_range , <EOL> } , context_processors ) <EOL> else : <EOL> c = RequestContext ( request , { <EOL> '<STR_LIT>' % template_object_name : queryset , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : False , <EOL> } , context_processors ) <EOL> if not allow_empty and len ( queryset ) == <NUM_LIT:0> : <EOL> raise Http404 <EOL> for key , value in extra_context . items ( ) : <EOL> if callable ( value ) : <EOL> c [ key ] = value ( ) <EOL> else : <EOL> c [ key ] = value <EOL> if not template_name : <EOL> model = queryset . model <EOL> template_name = "<STR_LIT>" % ( model . _meta . app_label , model . _meta . object_name . lower ( ) ) <EOL> t = template_loader . get_template ( template_name ) <EOL> return HttpResponse ( t . render ( c ) , mimetype = mimetype ) <EOL> def object_detail ( request , queryset , object_id = None , slug = None , <EOL> slug_field = '<STR_LIT>' , template_name = None , template_name_field = None , <EOL> template_loader = loader , extra_context = None , <EOL> context_processors = None , template_object_name = '<STR_LIT:object>' , <EOL> mimetype = None ) : <EOL> """<STR_LIT>""" <EOL> if extra_context is None : extra_context = { } <EOL> model = queryset . model <EOL> if object_id : <EOL> queryset = queryset . filter ( pk = object_id ) <EOL> elif slug and slug_field : <EOL> queryset = queryset . filter ( ** { slug_field : slug } ) <EOL> else : <EOL> raise AttributeError ( "<STR_LIT>" ) <EOL> try : <EOL> obj = queryset . get ( ) <EOL> except ObjectDoesNotExist : <EOL> raise Http404 ( "<STR_LIT>" % ( model . _meta . verbose_name ) ) <EOL> if not template_name : <EOL> template_name = "<STR_LIT>" % ( model . _meta . app_label , model . _meta . object_name . lower ( ) ) <EOL> if template_name_field : <EOL> template_name_list = [ getattr ( obj , template_name_field ) , template_name ] <EOL> t = template_loader . select_template ( template_name_list ) <EOL> else : <EOL> t = template_loader . get_template ( template_name ) <EOL> c = RequestContext ( request , { <EOL> template_object_name : obj , <EOL> } , context_processors ) <EOL> for key , value in extra_context . items ( ) : <EOL> if callable ( value ) : <EOL> c [ key ] = value ( ) <EOL> else : <EOL> c [ key ] = value <EOL> response = HttpResponse ( t . render ( c ) , mimetype = mimetype ) <EOL> populate_xheaders ( request , response , model , getattr ( obj , obj . _meta . pk . name ) ) <EOL> return response </s>
|
<s> from django . db . models import sql <EOL> from django . db . models . loading import cache <EOL> from django . db . models . query import CollectedObjects <EOL> from django . db . models . query_utils import CyclicDependency <EOL> from django . test import TestCase <EOL> from models import A , B , C , D , E , F <EOL> class DeleteTests ( TestCase ) : <EOL> def clear_rel_obj_caches ( self , * models ) : <EOL> for m in models : <EOL> if hasattr ( m . _meta , '<STR_LIT>' ) : <EOL> del m . _meta . _related_objects_cache <EOL> def order_models ( self , * models ) : <EOL> cache . app_models [ "<STR_LIT>" ] . keyOrder = models <EOL> def setUp ( self ) : <EOL> self . order_models ( "<STR_LIT:a>" , "<STR_LIT:b>" , "<STR_LIT:c>" , "<STR_LIT:d>" , "<STR_LIT:e>" , "<STR_LIT:f>" ) <EOL> self . clear_rel_obj_caches ( A , B , C , D , E , F ) <EOL> def tearDown ( self ) : <EOL> self . order_models ( "<STR_LIT:a>" , "<STR_LIT:b>" , "<STR_LIT:c>" , "<STR_LIT:d>" , "<STR_LIT:e>" , "<STR_LIT:f>" ) <EOL> self . clear_rel_obj_caches ( A , B , C , D , E , F ) <EOL> def test_collected_objects ( self ) : <EOL> g = CollectedObjects ( ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , None ) ) <EOL> self . assertEqual ( g [ "<STR_LIT>" ] , { <NUM_LIT:1> : "<STR_LIT>" } ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:2> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertEqual ( g [ "<STR_LIT>" ] , { <NUM_LIT:1> : "<STR_LIT>" , <NUM_LIT:2> : "<STR_LIT>" } ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertTrue ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertEqual ( g . ordered_keys ( ) , [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> self . assertTrue ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertRaises ( CyclicDependency , g . ordered_keys ) <EOL> def test_delete ( self ) : <EOL> a1 = A . objects . create ( ) <EOL> b1 = B . objects . create ( a = a1 ) <EOL> c1 = C . objects . create ( b = b1 ) <EOL> d1 = D . objects . create ( c = c1 , a = a1 ) <EOL> o = CollectedObjects ( ) <EOL> a1 . _collect_sub_objects ( o ) <EOL> self . assertEqual ( o . keys ( ) , [ D , C , B , A ] ) <EOL> a1 . delete ( ) <EOL> self . order_models ( "<STR_LIT:d>" , "<STR_LIT:c>" , "<STR_LIT:b>" , "<STR_LIT:a>" ) <EOL> self . clear_rel_obj_caches ( A , B , C , D ) <EOL> a2 = A . objects . create ( ) <EOL> b2 = B . objects . create ( a = a2 ) <EOL> c2 = C . objects . create ( b = b2 ) <EOL> d2 = D . objects . create ( c = c2 , a = a2 ) <EOL> o = CollectedObjects ( ) <EOL> a2 . _collect_sub_objects ( o ) <EOL> self . assertEqual ( o . keys ( ) , [ D , C , B , A ] ) <EOL> a2 . delete ( ) <EOL> def test_collected_objects_null ( self ) : <EOL> g = CollectedObjects ( ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , None ) ) <EOL> self . assertFalse ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" , nullable = True ) ) <EOL> self . assertTrue ( g . add ( "<STR_LIT>" , <NUM_LIT:1> , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> self . assertEqual ( g . ordered_keys ( ) , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> def test_delete_nullable ( self ) : <EOL> e1 = E . objects . create ( ) <EOL> f1 = F . objects . create ( e = e1 ) <EOL> e1 . f = f1 <EOL> e1 . save ( ) <EOL> o = CollectedObjects ( ) <EOL> e1 . _collect_sub_objects ( o ) <EOL> self . assertEqual ( o . keys ( ) , [ F , E ] ) <EOL> logged = [ ] <EOL> class LoggingUpdateQuery ( sql . UpdateQuery ) : <EOL> def clear_related ( self , related_field , pk_list , using ) : <EOL> logged . append ( related_field . name ) <EOL> return super ( LoggingUpdateQuery , self ) . clear_related ( related_field , pk_list , using ) <EOL> original = sql . UpdateQuery <EOL> sql . UpdateQuery = LoggingUpdateQuery <EOL> e1 . delete ( ) <EOL> self . assertEqual ( logged , [ "<STR_LIT:f>" ] ) <EOL> logged = [ ] <EOL> e2 = E . objects . create ( ) <EOL> f2 = F . objects . create ( e = e2 ) <EOL> e2 . f = f2 <EOL> e2 . save ( ) <EOL> o = CollectedObjects ( ) <EOL> f2 . _collect_sub_objects ( o ) <EOL> self . assertEqual ( o . keys ( ) , [ F , E ] ) <EOL> f2 . delete ( ) <EOL> self . assertEqual ( logged , [ "<STR_LIT:f>" ] ) <EOL> logged = [ ] <EOL> sql . UpdateQuery = original </s>
|
<s> """<STR_LIT>""" <EOL> from django . db import models <EOL> class Article ( models . Model ) : <EOL> headline = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> pub_date = models . DateTimeField ( ) <EOL> class Meta : <EOL> ordering = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def __unicode__ ( self ) : <EOL> return self . headline </s>
|
<s> from operator import attrgetter <EOL> from django . conf import settings <EOL> from django . core . exceptions import FieldError <EOL> from django . db import connection <EOL> from django . test import TestCase <EOL> from models import ( Chef , CommonInfo , ItalianRestaurant , ParkingLot , Place , <EOL> Post , Restaurant , Student , StudentWorker , Supplier , Worker , MixinModel ) <EOL> class ModelInheritanceTests ( TestCase ) : <EOL> def test_abstract ( self ) : <EOL> w1 = Worker . objects . create ( name = "<STR_LIT>" , age = <NUM_LIT> , job = "<STR_LIT>" ) <EOL> w2 = Worker . objects . create ( name = "<STR_LIT>" , age = <NUM_LIT> , job = "<STR_LIT>" ) <EOL> s = Student . objects . create ( name = "<STR_LIT>" , age = <NUM_LIT:5> , school_class = "<STR_LIT>" ) <EOL> self . assertEqual ( unicode ( w1 ) , "<STR_LIT>" ) <EOL> self . assertEqual ( unicode ( s ) , "<STR_LIT>" ) <EOL> self . assertQuerysetEqual ( <EOL> Worker . objects . values ( "<STR_LIT:name>" ) , [ <EOL> { "<STR_LIT:name>" : "<STR_LIT>" } , <EOL> { "<STR_LIT:name>" : "<STR_LIT>" } , <EOL> ] , <EOL> lambda o : o <EOL> ) <EOL> self . assertEqual ( Student . _meta . ordering , [ ] ) <EOL> self . assertRaises ( AttributeError , lambda : CommonInfo . objects . all ( ) ) <EOL> self . assertRaises ( Student . DoesNotExist , <EOL> StudentWorker . objects . get , pk = <NUM_LIT> <EOL> ) <EOL> self . assertRaises ( Worker . DoesNotExist , <EOL> StudentWorker . objects . get , pk = <NUM_LIT> <EOL> ) <EOL> sw1 = StudentWorker ( ) <EOL> sw1 . name = "<STR_LIT>" <EOL> sw1 . age = <NUM_LIT> <EOL> sw1 . save ( ) <EOL> sw2 = StudentWorker ( ) <EOL> sw2 . name = "<STR_LIT>" <EOL> sw2 . age = <NUM_LIT> <EOL> sw2 . save ( ) <EOL> self . assertRaises ( Student . MultipleObjectsReturned , <EOL> StudentWorker . objects . get , pk__lt = sw2 . pk + <NUM_LIT:100> <EOL> ) <EOL> self . assertRaises ( Worker . MultipleObjectsReturned , <EOL> StudentWorker . objects . get , pk__lt = sw2 . pk + <NUM_LIT:100> <EOL> ) <EOL> def test_multiple_table ( self ) : <EOL> post = Post . objects . create ( title = "<STR_LIT>" ) <EOL> post . attached_comment_set . create ( content = "<STR_LIT>" , is_spam = True ) <EOL> post . attached_link_set . create ( <EOL> content = "<STR_LIT>" , <EOL> url = "<STR_LIT>" <EOL> ) <EOL> self . assertRaises ( AttributeError , <EOL> getattr , post , "<STR_LIT>" <EOL> ) <EOL> p1 = Place . objects . create ( name = "<STR_LIT>" , address = "<STR_LIT>" ) <EOL> p2 = Place . objects . create ( name = "<STR_LIT>" , address = "<STR_LIT>" ) <EOL> r = Restaurant . objects . create ( <EOL> name = "<STR_LIT>" , <EOL> address = "<STR_LIT>" , <EOL> serves_hot_dogs = True , <EOL> serves_pizza = False , <EOL> rating = <NUM_LIT:2> <EOL> ) <EOL> c = Chef . objects . create ( name = "<STR_LIT>" ) <EOL> ir = ItalianRestaurant . objects . create ( <EOL> name = "<STR_LIT>" , <EOL> address = "<STR_LIT>" , <EOL> serves_hot_dogs = False , <EOL> serves_pizza = False , <EOL> serves_gnocchi = True , <EOL> rating = <NUM_LIT:4> , <EOL> chef = c <EOL> ) <EOL> self . assertQuerysetEqual ( <EOL> ItalianRestaurant . objects . filter ( address = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> ir . address = "<STR_LIT>" <EOL> ir . save ( ) <EOL> self . assertQuerysetEqual ( <EOL> ItalianRestaurant . objects . filter ( address = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> self . assertEqual ( <EOL> [ f . name for f in Restaurant . _meta . fields ] , <EOL> [ "<STR_LIT:id>" , "<STR_LIT:name>" , "<STR_LIT:address>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> ) <EOL> self . assertEqual ( <EOL> [ f . name for f in ItalianRestaurant . _meta . fields ] , <EOL> [ "<STR_LIT:id>" , "<STR_LIT:name>" , "<STR_LIT:address>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] , <EOL> ) <EOL> self . assertEqual ( Restaurant . _meta . ordering , [ "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( Place . objects . filter ( supplier__name = "<STR_LIT:foo>" ) , [ ] ) <EOL> self . assertRaises ( FieldError , <EOL> Restaurant . objects . filter , supplier__name = "<STR_LIT:foo>" <EOL> ) <EOL> self . assertQuerysetEqual ( <EOL> Restaurant . objects . filter ( name = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> self . assertQuerysetEqual ( <EOL> ItalianRestaurant . objects . filter ( address = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> p = Place . objects . get ( name = "<STR_LIT>" ) <EOL> self . assertTrue ( type ( p ) is Place ) <EOL> self . assertEqual ( <EOL> p . restaurant , Restaurant . objects . get ( name = "<STR_LIT>" ) <EOL> ) <EOL> self . assertEqual ( <EOL> Place . objects . get ( name = "<STR_LIT>" ) . restaurant . italianrestaurant , <EOL> ItalianRestaurant . objects . get ( name = "<STR_LIT>" ) <EOL> ) <EOL> self . assertEqual ( <EOL> Restaurant . objects . get ( name = "<STR_LIT>" ) . italianrestaurant , <EOL> ItalianRestaurant . objects . get ( name = "<STR_LIT>" ) <EOL> ) <EOL> self . assertRaises ( ItalianRestaurant . DoesNotExist , <EOL> lambda : p . restaurant . italianrestaurant <EOL> ) <EOL> self . assertRaises ( Place . DoesNotExist , <EOL> ItalianRestaurant . objects . get , name = "<STR_LIT>" <EOL> ) <EOL> self . assertRaises ( Place . MultipleObjectsReturned , <EOL> Restaurant . objects . get , id__lt = <NUM_LIT> <EOL> ) <EOL> s1 = Supplier . objects . create ( name = "<STR_LIT>" , address = "<STR_LIT>" ) <EOL> s1 . customers = [ r , ir ] <EOL> s2 = Supplier . objects . create ( name = "<STR_LIT>" , address = "<STR_LIT>" ) <EOL> s2 . customers = [ ir ] <EOL> p = Place . objects . get ( name = "<STR_LIT>" ) <EOL> self . assertRaises ( Restaurant . DoesNotExist , <EOL> lambda : p . restaurant <EOL> ) <EOL> self . assertEqual ( p . supplier , s1 ) <EOL> self . assertQuerysetEqual ( <EOL> ir . provider . order_by ( "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> self . assertQuerysetEqual ( <EOL> Restaurant . objects . filter ( provider__name__contains = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) <EOL> ) <EOL> self . assertQuerysetEqual ( <EOL> ItalianRestaurant . objects . filter ( provider__name__contains = "<STR_LIT>" ) , [ <EOL> "<STR_LIT>" , <EOL> ] , <EOL> attrgetter ( "<STR_LIT:name>" ) , <EOL> ) <EOL> park1 = ParkingLot . objects . create ( <EOL> name = "<STR_LIT>" , address = "<STR_LIT>" , main_site = s1 <EOL> ) <EOL> park2 = ParkingLot . objects . create ( <EOL> name = "<STR_LIT>" , address = "<STR_LIT>" , main_site = ir <EOL> ) <EOL> self . assertEqual ( <EOL> Restaurant . objects . get ( lot__name = "<STR_LIT>" ) . name , <EOL> "<STR_LIT>" <EOL> ) <EOL> rows = Restaurant . objects . filter ( <EOL> serves_hot_dogs = True , name__contains = "<STR_LIT:D>" <EOL> ) . update ( <EOL> name = "<STR_LIT>" , serves_hot_dogs = False <EOL> ) <EOL> self . assertEqual ( rows , <NUM_LIT:1> ) <EOL> r1 = Restaurant . objects . get ( pk = r . pk ) <EOL> self . assertFalse ( r1 . serves_hot_dogs ) <EOL> self . assertEqual ( r1 . name , "<STR_LIT>" ) <EOL> self . assertQuerysetEqual ( <EOL> ItalianRestaurant . objects . values ( "<STR_LIT:name>" , "<STR_LIT>" ) , [ <EOL> { "<STR_LIT>" : <NUM_LIT:4> , "<STR_LIT:name>" : "<STR_LIT>" } <EOL> ] , <EOL> lambda o : o <EOL> ) <EOL> old_DEBUG = settings . DEBUG <EOL> try : <EOL> settings . DEBUG = True <EOL> starting_queries = len ( connection . queries ) <EOL> ItalianRestaurant . objects . all ( ) [ <NUM_LIT:0> ] . chef <EOL> self . assertEqual ( len ( connection . queries ) - starting_queries , <NUM_LIT:2> ) <EOL> starting_queries = len ( connection . queries ) <EOL> ItalianRestaurant . objects . select_related ( "<STR_LIT>" ) [ <NUM_LIT:0> ] . chef <EOL> self . assertEqual ( len ( connection . queries ) - starting_queries , <NUM_LIT:1> ) <EOL> finally : <EOL> settings . DEBUG = old_DEBUG <EOL> def test_mixin_init ( self ) : <EOL> m = MixinModel ( ) <EOL> self . assertEqual ( m . other_attr , <NUM_LIT:1> ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . db import models <EOL> class Thing ( models . Model ) : <EOL> when = models . CharField ( max_length = <NUM_LIT:1> , primary_key = True ) <EOL> join = models . CharField ( max_length = <NUM_LIT:1> ) <EOL> like = models . CharField ( max_length = <NUM_LIT:1> ) <EOL> drop = models . CharField ( max_length = <NUM_LIT:1> ) <EOL> alter = models . CharField ( max_length = <NUM_LIT:1> ) <EOL> having = models . CharField ( max_length = <NUM_LIT:1> ) <EOL> where = models . DateField ( max_length = <NUM_LIT:1> ) <EOL> has_hyphen = models . CharField ( max_length = <NUM_LIT:1> , db_column = '<STR_LIT>' ) <EOL> class Meta : <EOL> db_table = '<STR_LIT>' <EOL> def __unicode__ ( self ) : <EOL> return self . when </s>
|
<s> from datetime import datetime <EOL> from django . core . exceptions import ValidationError <EOL> from django . db import models <EOL> from django . test import TestCase <EOL> def validate_answer_to_universe ( value ) : <EOL> if value != <NUM_LIT> : <EOL> raise ValidationError ( '<STR_LIT>' , code = '<STR_LIT>' ) <EOL> class ModelToValidate ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> created = models . DateTimeField ( default = datetime . now ) <EOL> number = models . IntegerField ( db_column = '<STR_LIT>' ) <EOL> parent = models . ForeignKey ( '<STR_LIT>' , blank = True , null = True , limit_choices_to = { '<STR_LIT>' : <NUM_LIT:10> } ) <EOL> email = models . EmailField ( blank = True ) <EOL> url = models . URLField ( blank = True ) <EOL> f_with_custom_validator = models . IntegerField ( blank = True , null = True , validators = [ validate_answer_to_universe ] ) <EOL> def clean ( self ) : <EOL> super ( ModelToValidate , self ) . clean ( ) <EOL> if self . number == <NUM_LIT:11> : <EOL> raise ValidationError ( '<STR_LIT>' ) <EOL> class UniqueFieldsModel ( models . Model ) : <EOL> unique_charfield = models . CharField ( max_length = <NUM_LIT:100> , unique = True ) <EOL> unique_integerfield = models . IntegerField ( unique = True ) <EOL> non_unique_field = models . IntegerField ( ) <EOL> class CustomPKModel ( models . Model ) : <EOL> my_pk_field = models . CharField ( max_length = <NUM_LIT:100> , primary_key = True ) <EOL> class UniqueTogetherModel ( models . Model ) : <EOL> cfield = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> ifield = models . IntegerField ( ) <EOL> efield = models . EmailField ( ) <EOL> class Meta : <EOL> unique_together = ( ( '<STR_LIT>' , '<STR_LIT>' , ) , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> class UniqueForDateModel ( models . Model ) : <EOL> start_date = models . DateField ( ) <EOL> end_date = models . DateTimeField ( ) <EOL> count = models . IntegerField ( unique_for_date = "<STR_LIT>" , unique_for_year = "<STR_LIT>" ) <EOL> order = models . IntegerField ( unique_for_month = "<STR_LIT>" ) <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> class CustomMessagesModel ( models . Model ) : <EOL> other = models . IntegerField ( blank = True , null = True ) <EOL> number = models . IntegerField ( db_column = '<STR_LIT>' , <EOL> error_messages = { '<STR_LIT:null>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> validators = [ validate_answer_to_universe ] <EOL> ) <EOL> class Author ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> class Article ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> author = models . ForeignKey ( Author ) <EOL> pub_date = models . DateTimeField ( blank = True ) <EOL> def clean ( self ) : <EOL> if self . pub_date is None : <EOL> self . pub_date = datetime . now ( ) <EOL> class Post ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:50> , unique_for_date = '<STR_LIT>' , blank = True ) <EOL> slug = models . CharField ( max_length = <NUM_LIT:50> , unique_for_year = '<STR_LIT>' , blank = True ) <EOL> subtitle = models . CharField ( max_length = <NUM_LIT:50> , unique_for_month = '<STR_LIT>' , blank = True ) <EOL> posted = models . DateField ( ) <EOL> def __unicode__ ( self ) : <EOL> return self . name <EOL> class FlexibleDatePost ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:50> , unique_for_date = '<STR_LIT>' , blank = True ) <EOL> slug = models . CharField ( max_length = <NUM_LIT:50> , unique_for_year = '<STR_LIT>' , blank = True ) <EOL> subtitle = models . CharField ( max_length = <NUM_LIT:50> , unique_for_month = '<STR_LIT>' , blank = True ) <EOL> posted = models . DateField ( blank = True , null = True ) </s>
|
<s> from datetime import datetime <EOL> import unittest <EOL> from django . conf import settings <EOL> from django . db import models <EOL> from django . utils . formats import localize <EOL> from django . test import TestCase <EOL> from django . contrib import admin <EOL> from django . contrib . admin . util import display_for_field , label_for_field , lookup_field <EOL> from django . contrib . admin . views . main import EMPTY_CHANGELIST_VALUE <EOL> from django . contrib . sites . models import Site <EOL> from django . contrib . admin . util import NestedObjects <EOL> from models import Article , Count , Event , Location <EOL> class NestedObjectsTests ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . n = NestedObjects ( ) <EOL> self . objs = [ Count . objects . create ( num = i ) for i in range ( <NUM_LIT:5> ) ] <EOL> def _check ( self , target ) : <EOL> self . assertEquals ( self . n . nested ( lambda obj : obj . num ) , target ) <EOL> def _add ( self , obj , parent = None ) : <EOL> self . n . add ( None , None , obj , None , parent ) <EOL> def test_unrelated_roots ( self ) : <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:1> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:2> ] , self . objs [ <NUM_LIT:1> ] ) <EOL> self . _check ( [ <NUM_LIT:0> , <NUM_LIT:1> , [ <NUM_LIT:2> ] ] ) <EOL> def test_siblings ( self ) : <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:1> ] , self . objs [ <NUM_LIT:0> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:2> ] , self . objs [ <NUM_LIT:0> ] ) <EOL> self . _check ( [ <NUM_LIT:0> , [ <NUM_LIT:1> , <NUM_LIT:2> ] ] ) <EOL> def test_duplicate_instances ( self ) : <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:1> ] ) <EOL> dupe = Count . objects . get ( num = <NUM_LIT:1> ) <EOL> self . _add ( dupe , self . objs [ <NUM_LIT:0> ] ) <EOL> self . _check ( [ <NUM_LIT:0> , <NUM_LIT:1> ] ) <EOL> def test_non_added_parent ( self ) : <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] , self . objs [ <NUM_LIT:1> ] ) <EOL> self . _check ( [ <NUM_LIT:0> ] ) <EOL> def test_cyclic ( self ) : <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] , self . objs [ <NUM_LIT:2> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:1> ] , self . objs [ <NUM_LIT:0> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:2> ] , self . objs [ <NUM_LIT:1> ] ) <EOL> self . _add ( self . objs [ <NUM_LIT:0> ] , self . objs [ <NUM_LIT:2> ] ) <EOL> self . _check ( [ <NUM_LIT:0> , [ <NUM_LIT:1> , [ <NUM_LIT:2> ] ] ] ) <EOL> class UtilTests ( unittest . TestCase ) : <EOL> def test_values_from_lookup_field ( self ) : <EOL> """<STR_LIT>""" <EOL> SITE_NAME = '<STR_LIT>' <EOL> TITLE_TEXT = '<STR_LIT>' <EOL> CREATED_DATE = datetime . min <EOL> ADMIN_METHOD = '<STR_LIT>' <EOL> SIMPLE_FUNCTION = '<STR_LIT>' <EOL> INSTANCE_ATTRIBUTE = '<STR_LIT>' <EOL> class MockModelAdmin ( object ) : <EOL> def get_admin_value ( self , obj ) : <EOL> return ADMIN_METHOD <EOL> simple_function = lambda obj : SIMPLE_FUNCTION <EOL> article = Article ( <EOL> site = Site ( domain = SITE_NAME ) , <EOL> title = TITLE_TEXT , <EOL> created = CREATED_DATE , <EOL> ) <EOL> article . non_field = INSTANCE_ATTRIBUTE <EOL> verifications = ( <EOL> ( '<STR_LIT>' , SITE_NAME ) , <EOL> ( '<STR_LIT>' , localize ( CREATED_DATE ) ) , <EOL> ( '<STR_LIT:title>' , TITLE_TEXT ) , <EOL> ( '<STR_LIT>' , ADMIN_METHOD ) , <EOL> ( simple_function , SIMPLE_FUNCTION ) , <EOL> ( '<STR_LIT>' , article . test_from_model ( ) ) , <EOL> ( '<STR_LIT>' , INSTANCE_ATTRIBUTE ) <EOL> ) <EOL> mock_admin = MockModelAdmin ( ) <EOL> for name , value in verifications : <EOL> field , attr , resolved_value = lookup_field ( name , article , mock_admin ) <EOL> if field is not None : <EOL> resolved_value = display_for_field ( resolved_value , field ) <EOL> self . assertEqual ( value , resolved_value ) <EOL> def test_null_display_for_field ( self ) : <EOL> """<STR_LIT>""" <EOL> display_value = display_for_field ( None , models . CharField ( ) ) <EOL> self . assertEqual ( display_value , EMPTY_CHANGELIST_VALUE ) <EOL> display_value = display_for_field ( None , models . CharField ( <EOL> choices = ( <EOL> ( None , "<STR_LIT>" ) , <EOL> ) <EOL> ) ) <EOL> self . assertEqual ( display_value , "<STR_LIT>" ) <EOL> display_value = display_for_field ( None , models . DateField ( ) ) <EOL> self . assertEqual ( display_value , EMPTY_CHANGELIST_VALUE ) <EOL> display_value = display_for_field ( None , models . TimeField ( ) ) <EOL> self . assertEqual ( display_value , EMPTY_CHANGELIST_VALUE ) <EOL> display_value = display_for_field ( None , models . NullBooleanField ( ) ) <EOL> expected = u'<STR_LIT>' % settings . ADMIN_MEDIA_PREFIX <EOL> self . assertEqual ( display_value , expected ) <EOL> display_value = display_for_field ( None , models . DecimalField ( ) ) <EOL> self . assertEqual ( display_value , EMPTY_CHANGELIST_VALUE ) <EOL> display_value = display_for_field ( None , models . FloatField ( ) ) <EOL> self . assertEqual ( display_value , EMPTY_CHANGELIST_VALUE ) <EOL> def test_label_for_field ( self ) : <EOL> """<STR_LIT>""" <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT:title>" , Article ) , <EOL> "<STR_LIT:title>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article , return_attr = True ) , <EOL> ( "<STR_LIT>" , None ) <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertRaises ( <EOL> AttributeError , <EOL> lambda : label_for_field ( "<STR_LIT>" , Article ) <EOL> ) <EOL> def test_callable ( obj ) : <EOL> return "<STR_LIT>" <EOL> self . assertEquals ( <EOL> label_for_field ( test_callable , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( test_callable , Article , return_attr = True ) , <EOL> ( "<STR_LIT>" , test_callable ) <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article , return_attr = True ) , <EOL> ( "<STR_LIT>" , Article . test_from_model ) <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( lambda x : "<STR_LIT>" , Article ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> class MockModelAdmin ( object ) : <EOL> def test_from_model ( self , obj ) : <EOL> return "<STR_LIT>" <EOL> test_from_model . short_description = "<STR_LIT>" <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article , model_admin = MockModelAdmin ) , <EOL> "<STR_LIT>" <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( "<STR_LIT>" , Article , <EOL> model_admin = MockModelAdmin , <EOL> return_attr = True <EOL> ) , <EOL> ( "<STR_LIT>" , MockModelAdmin . test_from_model ) <EOL> ) <EOL> def test_related_name ( self ) : <EOL> """<STR_LIT>""" <EOL> self . assertEquals ( <EOL> label_for_field ( '<STR_LIT:location>' , Event , return_attr = True ) , <EOL> ( '<STR_LIT:location>' , None ) , <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( '<STR_LIT>' , Location , return_attr = True ) , <EOL> ( '<STR_LIT>' , None ) , <EOL> ) <EOL> self . assertEquals ( <EOL> label_for_field ( '<STR_LIT>' , Event , return_attr = True ) , <EOL> ( '<STR_LIT>' , None ) , <EOL> ) </s>
|
<s> from django . conf . urls . defaults import * <EOL> import views <EOL> urlpatterns = patterns ( '<STR_LIT>' , <EOL> ( r'<STR_LIT>' , views . file_upload_view ) , <EOL> ( r'<STR_LIT>' , views . file_upload_view_verify ) , <EOL> ( r'<STR_LIT>' , views . file_upload_unicode_name ) , <EOL> ( r'<STR_LIT>' , views . file_upload_echo ) , <EOL> ( r'<STR_LIT>' , views . file_upload_quota ) , <EOL> ( r'<STR_LIT>' , views . file_upload_quota_broken ) , <EOL> ( r'<STR_LIT>' , views . file_upload_getlist_count ) , <EOL> ( r'<STR_LIT>' , views . file_upload_errors ) , <EOL> ) </s>
|
<s> from django . contrib . localflavor . sk . forms import ( SKRegionSelect , <EOL> SKPostalCodeField , SKDistrictSelect ) <EOL> from utils import LocalFlavorTestCase <EOL> class SKLocalFlavorTests ( LocalFlavorTestCase ) : <EOL> def test_SKRegionSelect ( self ) : <EOL> f = SKRegionSelect ( ) <EOL> out = u'''<STR_LIT>''' <EOL> self . assertEqual ( f . render ( '<STR_LIT>' , '<STR_LIT>' ) , out ) <EOL> def test_SKDistrictSelect ( self ) : <EOL> f = SKDistrictSelect ( ) <EOL> out = u'''<STR_LIT>''' <EOL> self . assertEqual ( f . render ( '<STR_LIT>' , '<STR_LIT>' ) , out ) <EOL> def test_SKPostalCodeField ( self ) : <EOL> error_format = [ u'<STR_LIT>' ] <EOL> valid = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> invalid = { <EOL> '<STR_LIT>' : error_format , <EOL> } <EOL> self . assertFieldOutput ( SKPostalCodeField , valid , invalid ) </s>
|
<s> from django . test import TestCase <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . db . models import Q <EOL> from models import * <EOL> class GenericRelationTests ( TestCase ) : <EOL> def test_inherited_models_content_type ( self ) : <EOL> """<STR_LIT>""" <EOL> p = Place . objects . create ( name = "<STR_LIT>" ) <EOL> r = Restaurant . objects . create ( name = "<STR_LIT>" ) <EOL> l1 = Link . objects . create ( content_object = p ) <EOL> l2 = Link . objects . create ( content_object = r ) <EOL> self . assertEqual ( list ( p . links . all ( ) ) , [ l1 ] ) <EOL> self . assertEqual ( list ( r . links . all ( ) ) , [ l2 ] ) <EOL> def test_reverse_relation_pk ( self ) : <EOL> """<STR_LIT>""" <EOL> p = Person . objects . create ( account = <NUM_LIT> , name = '<STR_LIT>' ) <EOL> a = Address . objects . create ( street = '<STR_LIT>' , <EOL> city = '<STR_LIT>' , state = '<STR_LIT>' , <EOL> zipcode = '<STR_LIT>' , content_object = p ) <EOL> qs = Person . objects . filter ( addresses__zipcode = '<STR_LIT>' ) <EOL> self . assertEqual ( <NUM_LIT:1> , qs . count ( ) ) <EOL> self . assertEqual ( '<STR_LIT>' , qs [ <NUM_LIT:0> ] . name ) <EOL> def test_charlink_delete ( self ) : <EOL> oddrel = OddRelation1 . objects . create ( name = '<STR_LIT>' ) <EOL> cl = CharLink . objects . create ( content_object = oddrel ) <EOL> oddrel . delete ( ) <EOL> def test_textlink_delete ( self ) : <EOL> oddrel = OddRelation2 . objects . create ( name = '<STR_LIT>' ) <EOL> tl = TextLink . objects . create ( content_object = oddrel ) <EOL> oddrel . delete ( ) <EOL> def test_q_object_or ( self ) : <EOL> """<STR_LIT>""" <EOL> note_contact = Contact . objects . create ( ) <EOL> org_contact = Contact . objects . create ( ) <EOL> note = Note . objects . create ( note = '<STR_LIT>' , content_object = note_contact ) <EOL> org = Organization . objects . create ( name = '<STR_LIT>' ) <EOL> org . contacts . add ( org_contact ) <EOL> qs = Contact . objects . filter ( Q ( notes__note__icontains = r'<STR_LIT>' ) | <EOL> Q ( organizations__name__icontains = r'<STR_LIT>' ) ) <EOL> self . assertTrue ( org_contact in qs ) <EOL> qs = Contact . objects . filter ( <EOL> Q ( organizations__name__icontains = r'<STR_LIT>' ) | <EOL> Q ( notes__note__icontains = r'<STR_LIT>' ) ) <EOL> self . assertTrue ( org_contact in qs ) </s>
|
<s> import os <EOL> import re <EOL> import shutil <EOL> from django . test import TestCase <EOL> from django . core import management <EOL> LOCALE = '<STR_LIT>' <EOL> class ExtractorTests ( TestCase ) : <EOL> PO_FILE = '<STR_LIT>' % LOCALE <EOL> def setUp ( self ) : <EOL> self . _cwd = os . getcwd ( ) <EOL> self . test_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) <EOL> def _rmrf ( self , dname ) : <EOL> if os . path . commonprefix ( [ self . test_dir , os . path . abspath ( dname ) ] ) != self . test_dir : <EOL> return <EOL> shutil . rmtree ( dname ) <EOL> def tearDown ( self ) : <EOL> os . chdir ( self . test_dir ) <EOL> try : <EOL> self . _rmrf ( '<STR_LIT>' % LOCALE ) <EOL> except OSError : <EOL> pass <EOL> os . chdir ( self . _cwd ) <EOL> def assertMsgId ( self , msgid , s ) : <EOL> return self . assert_ ( re . search ( '<STR_LIT>' % msgid , s , re . MULTILINE ) ) <EOL> def assertNotMsgId ( self , msgid , s ) : <EOL> return self . assert_ ( not re . search ( '<STR_LIT>' % msgid , s , re . MULTILINE ) ) <EOL> class TemplateExtractorTests ( ExtractorTests ) : <EOL> def test_templatize ( self ) : <EOL> os . chdir ( self . test_dir ) <EOL> management . call_command ( '<STR_LIT>' , locale = LOCALE , verbosity = <NUM_LIT:0> ) <EOL> self . assert_ ( os . path . exists ( self . PO_FILE ) ) <EOL> po_contents = open ( self . PO_FILE , '<STR_LIT:r>' ) . read ( ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> class JavascriptExtractorTests ( ExtractorTests ) : <EOL> PO_FILE = '<STR_LIT>' % LOCALE <EOL> def test_javascript_literals ( self ) : <EOL> os . chdir ( self . test_dir ) <EOL> management . call_command ( '<STR_LIT>' , domain = '<STR_LIT>' , locale = LOCALE , verbosity = <NUM_LIT:0> ) <EOL> self . assert_ ( os . path . exists ( self . PO_FILE ) ) <EOL> po_contents = open ( self . PO_FILE , '<STR_LIT:r>' ) . read ( ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> class IgnoredExtractorTests ( ExtractorTests ) : <EOL> def test_ignore_option ( self ) : <EOL> os . chdir ( self . test_dir ) <EOL> management . call_command ( '<STR_LIT>' , locale = LOCALE , verbosity = <NUM_LIT:0> , ignore_patterns = [ '<STR_LIT>' ] ) <EOL> self . assert_ ( os . path . exists ( self . PO_FILE ) ) <EOL> po_contents = open ( self . PO_FILE , '<STR_LIT:r>' ) . read ( ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> self . assertNotMsgId ( '<STR_LIT>' , po_contents ) <EOL> class SymlinkExtractorTests ( ExtractorTests ) : <EOL> def setUp ( self ) : <EOL> self . _cwd = os . getcwd ( ) <EOL> self . test_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) <EOL> self . symlinked_dir = os . path . join ( self . test_dir , '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> super ( SymlinkExtractorTests , self ) . tearDown ( ) <EOL> os . chdir ( self . test_dir ) <EOL> try : <EOL> os . remove ( self . symlinked_dir ) <EOL> except OSError : <EOL> pass <EOL> os . chdir ( self . _cwd ) <EOL> def test_symlink ( self ) : <EOL> if hasattr ( os , '<STR_LIT>' ) : <EOL> if os . path . exists ( self . symlinked_dir ) : <EOL> self . assert_ ( os . path . islink ( self . symlinked_dir ) ) <EOL> else : <EOL> os . symlink ( os . path . join ( self . test_dir , '<STR_LIT>' ) , self . symlinked_dir ) <EOL> os . chdir ( self . test_dir ) <EOL> management . call_command ( '<STR_LIT>' , locale = LOCALE , verbosity = <NUM_LIT:0> , symlinks = True ) <EOL> self . assert_ ( os . path . exists ( self . PO_FILE ) ) <EOL> po_contents = open ( self . PO_FILE , '<STR_LIT:r>' ) . read ( ) <EOL> self . assertMsgId ( '<STR_LIT>' , po_contents ) <EOL> self . assert_ ( '<STR_LIT>' in po_contents ) <EOL> class CopyPluralFormsExtractorTests ( ExtractorTests ) : <EOL> def test_copy_plural_forms ( self ) : <EOL> os . chdir ( self . test_dir ) <EOL> management . call_command ( '<STR_LIT>' , locale = LOCALE , verbosity = <NUM_LIT:0> ) <EOL> self . assert_ ( os . path . exists ( self . PO_FILE ) ) <EOL> po_contents = open ( self . PO_FILE , '<STR_LIT:r>' ) . read ( ) <EOL> self . assert_ ( '<STR_LIT>' in po_contents ) </s>
|
<s> from datetime import date <EOL> from django . db import models <EOL> from django . contrib . auth . models import User <EOL> class Band ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> bio = models . TextField ( ) <EOL> sign_date = models . DateField ( ) <EOL> def __unicode__ ( self ) : <EOL> return self . name <EOL> class Concert ( models . Model ) : <EOL> main_band = models . ForeignKey ( Band , related_name = '<STR_LIT>' ) <EOL> opening_band = models . ForeignKey ( Band , related_name = '<STR_LIT>' , <EOL> blank = True ) <EOL> day = models . CharField ( max_length = <NUM_LIT:3> , choices = ( ( <NUM_LIT:1> , '<STR_LIT>' ) , ( <NUM_LIT:2> , '<STR_LIT>' ) ) ) <EOL> transport = models . CharField ( max_length = <NUM_LIT:100> , choices = ( <EOL> ( <NUM_LIT:1> , '<STR_LIT>' ) , <EOL> ( <NUM_LIT:2> , '<STR_LIT>' ) , <EOL> ( <NUM_LIT:3> , '<STR_LIT>' ) <EOL> ) , blank = True ) <EOL> class ValidationTestModel ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> slug = models . SlugField ( ) <EOL> users = models . ManyToManyField ( User ) <EOL> state = models . CharField ( max_length = <NUM_LIT:2> , choices = ( ( "<STR_LIT>" , "<STR_LIT>" ) , ( "<STR_LIT>" , "<STR_LIT>" ) ) ) <EOL> is_active = models . BooleanField ( ) <EOL> pub_date = models . DateTimeField ( ) <EOL> band = models . ForeignKey ( Band ) <EOL> class ValidationTestInlineModel ( models . Model ) : <EOL> parent = models . ForeignKey ( ValidationTestModel ) </s>
|
<s> """<STR_LIT>""" <EOL> import os <EOL> import django <EOL> from django . test import TestCase <EOL> from django . core . handlers . wsgi import WSGIHandler <EOL> from django . core . servers . basehttp import AdminMediaHandler <EOL> class AdminMediaHandlerTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . admin_media_file_path = os . path . abspath ( <EOL> os . path . join ( django . __path__ [ <NUM_LIT:0> ] , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> ) <EOL> self . handler = AdminMediaHandler ( WSGIHandler ( ) ) <EOL> def test_media_urls ( self ) : <EOL> """<STR_LIT>""" <EOL> data = ( <EOL> ( '<STR_LIT>' , ( '<STR_LIT>' , '<STR_LIT>' ) ) , <EOL> ) <EOL> bad_data = ( ) <EOL> if os . sep == '<STR_LIT:/>' : <EOL> data += ( <EOL> ( '<STR_LIT>' , ( '<STR_LIT>' , '<STR_LIT>' ) ) , <EOL> ) <EOL> bad_data += ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> elif os . sep == '<STR_LIT:\\>' : <EOL> bad_data += ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ) <EOL> for url , path_tuple in data : <EOL> try : <EOL> output = self . handler . file_path ( url ) <EOL> except ValueError : <EOL> self . fail ( "<STR_LIT>" <EOL> "<STR_LIT>" % url ) <EOL> rel_path = os . path . join ( * path_tuple ) <EOL> desired = os . path . normcase ( <EOL> os . path . join ( self . admin_media_file_path , rel_path ) ) <EOL> self . assertEqual ( output , desired , <EOL> "<STR_LIT>" % ( output , desired , url ) ) <EOL> for url in bad_data : <EOL> try : <EOL> output = self . handler . file_path ( url ) <EOL> except ValueError : <EOL> continue <EOL> self . fail ( '<STR_LIT>' <EOL> % url ) </s>
|
<s> from django . test import TestCase <EOL> class DecoratorFromMiddlewareTests ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_process_view_middleware ( self ) : <EOL> """<STR_LIT>""" <EOL> self . client . get ( '<STR_LIT>' ) <EOL> def test_callable_process_view_middleware ( self ) : <EOL> """<STR_LIT>""" <EOL> self . client . get ( '<STR_LIT>' ) </s>
|
<s> DATE_FORMAT = '<STR_LIT>' <EOL> TIME_FORMAT = '<STR_LIT>' <EOL> DATETIME_FORMAT = '<STR_LIT>' <EOL> YEAR_MONTH_FORMAT = '<STR_LIT>' <EOL> MONTH_DAY_FORMAT = '<STR_LIT>' <EOL> SHORT_DATE_FORMAT = '<STR_LIT>' <EOL> SHORT_DATETIME_FORMAT = '<STR_LIT>' <EOL> DECIMAL_SEPARATOR = '<STR_LIT:U+002C>' <EOL> THOUSAND_SEPARATOR = '<STR_LIT:.>' </s>
|
<s> from django . db import models <EOL> from django . db . models . sql . constants import LOOKUP_SEP <EOL> from django . db . models . deletion import Collector <EOL> from django . db . models . related import RelatedObject <EOL> from django . forms . forms import pretty_name <EOL> from django . utils import formats <EOL> from django . utils . html import escape <EOL> from django . utils . safestring import mark_safe <EOL> from django . utils . text import capfirst <EOL> from django . utils . encoding import force_unicode , smart_unicode , smart_str <EOL> from django . utils . translation import ungettext <EOL> from django . core . urlresolvers import reverse <EOL> def quote ( s ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( s , basestring ) : <EOL> return s <EOL> res = list ( s ) <EOL> for i in range ( len ( res ) ) : <EOL> c = res [ i ] <EOL> if c in """<STR_LIT>""" : <EOL> res [ i ] = '<STR_LIT>' % ord ( c ) <EOL> return '<STR_LIT>' . join ( res ) <EOL> def unquote ( s ) : <EOL> """<STR_LIT>""" <EOL> mychr = chr <EOL> myatoi = int <EOL> list = s . split ( '<STR_LIT:_>' ) <EOL> res = [ list [ <NUM_LIT:0> ] ] <EOL> myappend = res . append <EOL> del list [ <NUM_LIT:0> ] <EOL> for item in list : <EOL> if item [ <NUM_LIT:1> : <NUM_LIT:2> ] : <EOL> try : <EOL> myappend ( mychr ( myatoi ( item [ : <NUM_LIT:2> ] , <NUM_LIT:16> ) ) + item [ <NUM_LIT:2> : ] ) <EOL> except ValueError : <EOL> myappend ( '<STR_LIT:_>' + item ) <EOL> else : <EOL> myappend ( '<STR_LIT:_>' + item ) <EOL> return "<STR_LIT>" . join ( res ) <EOL> def flatten_fieldsets ( fieldsets ) : <EOL> """<STR_LIT>""" <EOL> field_names = [ ] <EOL> for name , opts in fieldsets : <EOL> for field in opts [ '<STR_LIT>' ] : <EOL> if type ( field ) == tuple : <EOL> field_names . extend ( field ) <EOL> else : <EOL> field_names . append ( field ) <EOL> return field_names <EOL> def get_deleted_objects ( objs , opts , user , admin_site , using ) : <EOL> """<STR_LIT>""" <EOL> collector = NestedObjects ( using = using ) <EOL> collector . collect ( objs ) <EOL> perms_needed = set ( ) <EOL> def format_callback ( obj ) : <EOL> has_admin = obj . __class__ in admin_site . _registry <EOL> opts = obj . _meta <EOL> if has_admin : <EOL> admin_url = reverse ( '<STR_LIT>' <EOL> % ( admin_site . name , <EOL> opts . app_label , <EOL> opts . object_name . lower ( ) ) , <EOL> None , ( quote ( obj . _get_pk_val ( ) ) , ) ) <EOL> p = '<STR_LIT>' % ( opts . app_label , <EOL> opts . get_delete_permission ( ) ) <EOL> if not user . has_perm ( p ) : <EOL> perms_needed . add ( opts . verbose_name ) <EOL> return mark_safe ( u'<STR_LIT>' % <EOL> ( escape ( capfirst ( opts . verbose_name ) ) , <EOL> admin_url , <EOL> escape ( obj ) ) ) <EOL> else : <EOL> return u'<STR_LIT>' % ( capfirst ( opts . verbose_name ) , <EOL> force_unicode ( obj ) ) <EOL> to_delete = collector . nested ( format_callback ) <EOL> protected = [ format_callback ( obj ) for obj in collector . protected ] <EOL> return to_delete , perms_needed , protected <EOL> class NestedObjects ( Collector ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( NestedObjects , self ) . __init__ ( * args , ** kwargs ) <EOL> self . edges = { } <EOL> self . protected = set ( ) <EOL> def add_edge ( self , source , target ) : <EOL> self . edges . setdefault ( source , [ ] ) . append ( target ) <EOL> def collect ( self , objs , source_attr = None , ** kwargs ) : <EOL> for obj in objs : <EOL> if source_attr : <EOL> self . add_edge ( getattr ( obj , source_attr ) , obj ) <EOL> else : <EOL> self . add_edge ( None , obj ) <EOL> try : <EOL> return super ( NestedObjects , self ) . collect ( objs , source_attr = source_attr , ** kwargs ) <EOL> except models . ProtectedError , e : <EOL> self . protected . update ( e . protected_objects ) <EOL> def related_objects ( self , related , objs ) : <EOL> qs = super ( NestedObjects , self ) . related_objects ( related , objs ) <EOL> return qs . select_related ( related . field . name ) <EOL> def _nested ( self , obj , seen , format_callback ) : <EOL> if obj in seen : <EOL> return [ ] <EOL> seen . add ( obj ) <EOL> children = [ ] <EOL> for child in self . edges . get ( obj , ( ) ) : <EOL> children . extend ( self . _nested ( child , seen , format_callback ) ) <EOL> if format_callback : <EOL> ret = [ format_callback ( obj ) ] <EOL> else : <EOL> ret = [ obj ] <EOL> if children : <EOL> ret . append ( children ) <EOL> return ret <EOL> def nested ( self , format_callback = None ) : <EOL> """<STR_LIT>""" <EOL> seen = set ( ) <EOL> roots = [ ] <EOL> for root in self . edges . get ( None , ( ) ) : <EOL> roots . extend ( self . _nested ( root , seen , format_callback ) ) <EOL> return roots <EOL> def model_format_dict ( obj ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( obj , ( models . Model , models . base . ModelBase ) ) : <EOL> opts = obj . _meta <EOL> elif isinstance ( obj , models . query . QuerySet ) : <EOL> opts = obj . model . _meta <EOL> else : <EOL> opts = obj <EOL> return { <EOL> '<STR_LIT>' : force_unicode ( opts . verbose_name ) , <EOL> '<STR_LIT>' : force_unicode ( opts . verbose_name_plural ) <EOL> } <EOL> def model_ngettext ( obj , n = None ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( obj , models . query . QuerySet ) : <EOL> if n is None : <EOL> n = obj . count ( ) <EOL> obj = obj . model <EOL> d = model_format_dict ( obj ) <EOL> singular , plural = d [ "<STR_LIT>" ] , d [ "<STR_LIT>" ] <EOL> return ungettext ( singular , plural , n or <NUM_LIT:0> ) <EOL> def lookup_field ( name , obj , model_admin = None ) : <EOL> opts = obj . _meta <EOL> try : <EOL> f = opts . get_field ( name ) <EOL> except models . FieldDoesNotExist : <EOL> if callable ( name ) : <EOL> attr = name <EOL> value = attr ( obj ) <EOL> elif ( model_admin is not None and hasattr ( model_admin , name ) and <EOL> not name == '<STR_LIT>' and not name == '<STR_LIT>' ) : <EOL> attr = getattr ( model_admin , name ) <EOL> value = attr ( obj ) <EOL> else : <EOL> attr = getattr ( obj , name ) <EOL> if callable ( attr ) : <EOL> value = attr ( ) <EOL> else : <EOL> value = attr <EOL> f = None <EOL> else : <EOL> attr = None <EOL> value = getattr ( obj , name ) <EOL> return f , attr , value <EOL> def label_for_field ( name , model , model_admin = None , return_attr = False ) : <EOL> attr = None <EOL> try : <EOL> field = model . _meta . get_field_by_name ( name ) [ <NUM_LIT:0> ] <EOL> if isinstance ( field , RelatedObject ) : <EOL> label = field . opts . verbose_name <EOL> else : <EOL> label = field . verbose_name <EOL> except models . FieldDoesNotExist : <EOL> if name == "<STR_LIT>" : <EOL> label = force_unicode ( model . _meta . verbose_name ) <EOL> elif name == "<STR_LIT>" : <EOL> label = smart_str ( model . _meta . verbose_name ) <EOL> else : <EOL> if callable ( name ) : <EOL> attr = name <EOL> elif model_admin is not None and hasattr ( model_admin , name ) : <EOL> attr = getattr ( model_admin , name ) <EOL> elif hasattr ( model , name ) : <EOL> attr = getattr ( model , name ) <EOL> else : <EOL> message = "<STR_LIT>" % ( name , model . _meta . object_name ) <EOL> if model_admin : <EOL> message += "<STR_LIT>" % ( model_admin . __class__ . __name__ , ) <EOL> raise AttributeError ( message ) <EOL> if hasattr ( attr , "<STR_LIT>" ) : <EOL> label = attr . short_description <EOL> elif callable ( attr ) : <EOL> if attr . __name__ == "<STR_LIT>" : <EOL> label = "<STR_LIT>" <EOL> else : <EOL> label = pretty_name ( attr . __name__ ) <EOL> else : <EOL> label = pretty_name ( name ) <EOL> if return_attr : <EOL> return ( label , attr ) <EOL> else : <EOL> return label <EOL> def help_text_for_field ( name , model ) : <EOL> try : <EOL> help_text = model . _meta . get_field_by_name ( name ) [ <NUM_LIT:0> ] . help_text <EOL> except models . FieldDoesNotExist : <EOL> help_text = "<STR_LIT>" <EOL> return smart_unicode ( help_text ) <EOL> def display_for_field ( value , field ) : <EOL> from django . contrib . admin . templatetags . admin_list import _boolean_icon <EOL> from django . contrib . admin . views . main import EMPTY_CHANGELIST_VALUE <EOL> if field . flatchoices : <EOL> return dict ( field . flatchoices ) . get ( value , EMPTY_CHANGELIST_VALUE ) <EOL> elif isinstance ( field , models . BooleanField ) or isinstance ( field , models . NullBooleanField ) : <EOL> return _boolean_icon ( value ) <EOL> elif value is None : <EOL> return EMPTY_CHANGELIST_VALUE <EOL> elif isinstance ( field , models . DateField ) or isinstance ( field , models . TimeField ) : <EOL> return formats . localize ( value ) <EOL> elif isinstance ( field , models . DecimalField ) : <EOL> return formats . number_format ( value , field . decimal_places ) <EOL> elif isinstance ( field , models . FloatField ) : <EOL> return formats . number_format ( value ) <EOL> else : <EOL> return smart_unicode ( value ) <EOL> class NotRelationField ( Exception ) : <EOL> pass <EOL> def get_model_from_relation ( field ) : <EOL> if isinstance ( field , models . related . RelatedObject ) : <EOL> return field . model <EOL> elif getattr ( field , '<STR_LIT>' ) : <EOL> return field . rel . to <EOL> else : <EOL> raise NotRelationField <EOL> def reverse_field_path ( model , path ) : <EOL> """<STR_LIT>""" <EOL> reversed_path = [ ] <EOL> parent = model <EOL> pieces = path . split ( LOOKUP_SEP ) <EOL> for piece in pieces : <EOL> field , model , direct , m2m = parent . _meta . get_field_by_name ( piece ) <EOL> if len ( reversed_path ) == len ( pieces ) - <NUM_LIT:1> : <EOL> try : <EOL> get_model_from_relation ( field ) <EOL> except NotRelationField : <EOL> break <EOL> if direct : <EOL> related_name = field . related_query_name ( ) <EOL> parent = field . rel . to <EOL> else : <EOL> related_name = field . field . name <EOL> parent = field . model <EOL> reversed_path . insert ( <NUM_LIT:0> , related_name ) <EOL> return ( parent , LOOKUP_SEP . join ( reversed_path ) ) <EOL> def get_fields_from_path ( model , path ) : <EOL> """<STR_LIT>""" <EOL> pieces = path . split ( LOOKUP_SEP ) <EOL> fields = [ ] <EOL> for piece in pieces : <EOL> if fields : <EOL> parent = get_model_from_relation ( fields [ - <NUM_LIT:1> ] ) <EOL> else : <EOL> parent = model <EOL> fields . append ( parent . _meta . get_field_by_name ( piece ) [ <NUM_LIT:0> ] ) <EOL> return fields <EOL> def remove_trailing_data_field ( fields ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> get_model_from_relation ( fields [ - <NUM_LIT:1> ] ) <EOL> except NotRelationField : <EOL> fields = fields [ : - <NUM_LIT:1> ] <EOL> return fields <EOL> def get_limit_choices_to_from_path ( model , path ) : <EOL> """<STR_LIT>""" <EOL> fields = get_fields_from_path ( model , path ) <EOL> fields = remove_trailing_data_field ( fields ) <EOL> limit_choices_to = ( <EOL> fields and hasattr ( fields [ - <NUM_LIT:1> ] , '<STR_LIT>' ) and <EOL> getattr ( fields [ - <NUM_LIT:1> ] . rel , '<STR_LIT>' , None ) ) <EOL> if not limit_choices_to : <EOL> return models . Q ( ) <EOL> elif isinstance ( limit_choices_to , models . Q ) : <EOL> return limit_choices_to <EOL> else : <EOL> return models . Q ( ** limit_choices_to ) </s>
|
<s> """<STR_LIT>""" <EOL> import urllib <EOL> import textwrap <EOL> from django . http import HttpResponseRedirect <EOL> from django . core import urlresolvers <EOL> from django . shortcuts import render_to_response <EOL> from django . template import RequestContext <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . contrib import comments <EOL> def next_redirect ( data , default , default_view , ** get_kwargs ) : <EOL> """<STR_LIT>""" <EOL> next = data . get ( "<STR_LIT>" , default ) <EOL> if next is None : <EOL> next = urlresolvers . reverse ( default_view ) <EOL> if get_kwargs : <EOL> if '<STR_LIT:#>' in next : <EOL> tmp = next . rsplit ( '<STR_LIT:#>' , <NUM_LIT:1> ) <EOL> next = tmp [ <NUM_LIT:0> ] <EOL> anchor = '<STR_LIT:#>' + tmp [ <NUM_LIT:1> ] <EOL> else : <EOL> anchor = '<STR_LIT>' <EOL> joiner = ( '<STR_LIT:?>' in next ) and '<STR_LIT:&>' or '<STR_LIT:?>' <EOL> next += joiner + urllib . urlencode ( get_kwargs ) + anchor <EOL> return HttpResponseRedirect ( next ) <EOL> def confirmation_view ( template , doc = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> def confirmed ( request ) : <EOL> comment = None <EOL> if '<STR_LIT:c>' in request . GET : <EOL> try : <EOL> comment = comments . get_model ( ) . objects . get ( pk = request . GET [ '<STR_LIT:c>' ] ) <EOL> except ( ObjectDoesNotExist , ValueError ) : <EOL> pass <EOL> return render_to_response ( template , <EOL> { '<STR_LIT>' : comment } , <EOL> context_instance = RequestContext ( request ) <EOL> ) <EOL> confirmed . __doc__ = textwrap . dedent ( """<STR_LIT>""" % ( doc , template ) <EOL> ) <EOL> return confirmed </s>
|
<s> """<STR_LIT>""" <EOL> from django . utils . unittest import TestSuite , TextTestRunner <EOL> import test_driver , test_ds , test_envelope , test_geom , test_srs <EOL> test_suites = [ test_driver . suite ( ) , <EOL> test_ds . suite ( ) , <EOL> test_envelope . suite ( ) , <EOL> test_geom . suite ( ) , <EOL> test_srs . suite ( ) , <EOL> ] <EOL> def suite ( ) : <EOL> "<STR_LIT>" <EOL> s = TestSuite ( ) <EOL> map ( s . addTest , test_suites ) <EOL> return s <EOL> def run ( verbosity = <NUM_LIT:1> ) : <EOL> "<STR_LIT>" <EOL> TextTestRunner ( verbosity = verbosity ) . run ( suite ( ) ) </s>
|
<s> """<STR_LIT>""" <EOL> import re <EOL> from django . core . validators import EMPTY_VALUES <EOL> from django . forms import ValidationError <EOL> from django . forms . fields import RegexField , Select <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> class BEPostalCodeField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( <EOL> '<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( BEPostalCodeField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) <EOL> class BEPhoneNumberField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( BEPhoneNumberField , self ) . __init__ ( r'<STR_LIT>' , <EOL> max_length = None , min_length = None , * args , ** kwargs ) <EOL> class BERegionSelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> from be_regions import REGION_CHOICES <EOL> super ( BERegionSelect , self ) . __init__ ( attrs , choices = REGION_CHOICES ) <EOL> class BEProvinceSelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> from be_provinces import PROVINCE_CHOICES <EOL> super ( BEProvinceSelect , self ) . __init__ ( attrs , choices = PROVINCE_CHOICES ) </s>
|
<s> from django . conf import settings <EOL> from django . contrib . sites . models import Site , RequestSite , get_current_site <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . http import HttpRequest <EOL> from django . test import TestCase <EOL> class SitesFrameworkTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> Site ( id = settings . SITE_ID , domain = "<STR_LIT>" , name = "<STR_LIT>" ) . save ( ) <EOL> self . old_Site_meta_installed = Site . _meta . installed <EOL> Site . _meta . installed = True <EOL> def tearDown ( self ) : <EOL> Site . _meta . installed = self . old_Site_meta_installed <EOL> def test_site_manager ( self ) : <EOL> s = Site . objects . get_current ( ) <EOL> self . assertTrue ( isinstance ( s , Site ) ) <EOL> s . delete ( ) <EOL> self . assertRaises ( ObjectDoesNotExist , Site . objects . get_current ) <EOL> def test_site_cache ( self ) : <EOL> site = Site . objects . get_current ( ) <EOL> self . assertEqual ( u"<STR_LIT>" , site . name ) <EOL> s2 = Site . objects . get ( id = settings . SITE_ID ) <EOL> s2 . name = "<STR_LIT>" <EOL> s2 . save ( ) <EOL> site = Site . objects . get_current ( ) <EOL> self . assertEqual ( u"<STR_LIT>" , site . name ) <EOL> def test_get_current_site ( self ) : <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> } <EOL> site = get_current_site ( request ) <EOL> self . assertTrue ( isinstance ( site , Site ) ) <EOL> self . assertEqual ( site . id , settings . SITE_ID ) <EOL> site . delete ( ) <EOL> self . assertRaises ( ObjectDoesNotExist , get_current_site , request ) <EOL> Site . _meta . installed = False <EOL> site = get_current_site ( request ) <EOL> self . assertTrue ( isinstance ( site , RequestSite ) ) <EOL> self . assertEqual ( site . name , u"<STR_LIT>" ) </s>
|
<s> from optparse import make_option <EOL> from django . conf import settings <EOL> from django . db import connections , router , transaction , models , DEFAULT_DB_ALIAS <EOL> from django . core . management import call_command <EOL> from django . core . management . base import NoArgsCommand , CommandError <EOL> from django . core . management . color import no_style <EOL> from django . core . management . sql import sql_flush , emit_post_sync_signal <EOL> from django . utils . importlib import import_module <EOL> class Command ( NoArgsCommand ) : <EOL> option_list = NoArgsCommand . option_list + ( <EOL> make_option ( '<STR_LIT>' , action = '<STR_LIT>' , dest = '<STR_LIT>' , default = True , <EOL> help = '<STR_LIT>' ) , <EOL> make_option ( '<STR_LIT>' , action = '<STR_LIT:store>' , dest = '<STR_LIT>' , <EOL> default = DEFAULT_DB_ALIAS , help = '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> ) <EOL> help = "<STR_LIT>" <EOL> def handle_noargs ( self , ** options ) : <EOL> db = options . get ( '<STR_LIT>' , DEFAULT_DB_ALIAS ) <EOL> connection = connections [ db ] <EOL> verbosity = int ( options . get ( '<STR_LIT>' , <NUM_LIT:1> ) ) <EOL> interactive = options . get ( '<STR_LIT>' ) <EOL> self . style = no_style ( ) <EOL> for app_name in settings . INSTALLED_APPS : <EOL> try : <EOL> import_module ( '<STR_LIT>' , app_name ) <EOL> except ImportError : <EOL> pass <EOL> sql_list = sql_flush ( self . style , connection , only_django = True ) <EOL> if interactive : <EOL> confirm = raw_input ( """<STR_LIT>""" % connection . settings_dict [ '<STR_LIT>' ] ) <EOL> else : <EOL> confirm = '<STR_LIT:yes>' <EOL> if confirm == '<STR_LIT:yes>' : <EOL> try : <EOL> cursor = connection . cursor ( ) <EOL> for sql in sql_list : <EOL> cursor . execute ( sql ) <EOL> except Exception , e : <EOL> transaction . rollback_unless_managed ( using = db ) <EOL> raise CommandError ( """<STR_LIT>""" % ( connection . settings_dict [ '<STR_LIT>' ] , e ) ) <EOL> transaction . commit_unless_managed ( using = db ) <EOL> all_models = [ ] <EOL> for app in models . get_apps ( ) : <EOL> all_models . extend ( [ <EOL> m for m in models . get_models ( app , include_auto_created = True ) <EOL> if router . allow_syncdb ( db , m ) <EOL> ] ) <EOL> emit_post_sync_signal ( set ( all_models ) , verbosity , interactive , db ) <EOL> kwargs = options . copy ( ) <EOL> kwargs [ '<STR_LIT>' ] = db <EOL> call_command ( '<STR_LIT>' , '<STR_LIT>' , ** kwargs ) <EOL> else : <EOL> print "<STR_LIT>" </s>
|
<s> from django . conf import settings <EOL> from django . core . exceptions import ObjectDoesNotExist , ImproperlyConfigured <EOL> from django . db import connection <EOL> from django . db . models . loading import get_apps , get_app , get_models , get_model , register_models <EOL> from django . db . models . query import Q <EOL> from django . db . models . expressions import F <EOL> from django . db . models . manager import Manager <EOL> from django . db . models . base import Model <EOL> from django . db . models . aggregates import * <EOL> from django . db . models . fields import * <EOL> from django . db . models . fields . subclassing import SubfieldBase <EOL> from django . db . models . fields . files import FileField , ImageField <EOL> from django . db . models . fields . related import ForeignKey , OneToOneField , ManyToManyField , ManyToOneRel , ManyToManyRel , OneToOneRel <EOL> from django . db . models . deletion import CASCADE , PROTECT , SET , SET_NULL , SET_DEFAULT , DO_NOTHING , ProtectedError <EOL> from django . db . models import signals <EOL> from django . utils . decorators import wraps <EOL> ADD , CHANGE , BOTH = <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> <EOL> def permalink ( func ) : <EOL> """<STR_LIT>""" <EOL> from django . core . urlresolvers import reverse <EOL> @ wraps ( func ) <EOL> def inner ( * args , ** kwargs ) : <EOL> bits = func ( * args , ** kwargs ) <EOL> return reverse ( bits [ <NUM_LIT:0> ] , None , * bits [ <NUM_LIT:1> : <NUM_LIT:3> ] ) <EOL> return inner </s>
|
<s> """<STR_LIT>""" <EOL> import itertools <EOL> import re <EOL> import random <EOL> from django . conf import settings <EOL> from django . core . urlresolvers import get_callable <EOL> from django . utils . cache import patch_vary_headers <EOL> from django . utils . hashcompat import md5_constructor <EOL> from django . utils . http import same_origin <EOL> from django . utils . log import getLogger <EOL> from django . utils . safestring import mark_safe <EOL> from django . utils . crypto import constant_time_compare <EOL> _POST_FORM_RE = re . compile ( r'<STR_LIT>' , re . IGNORECASE ) <EOL> _HTML_TYPES = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> logger = getLogger ( '<STR_LIT>' ) <EOL> if hasattr ( random , '<STR_LIT>' ) : <EOL> randrange = random . SystemRandom ( ) . randrange <EOL> else : <EOL> randrange = random . randrange <EOL> _MAX_CSRF_KEY = <NUM_LIT> L <EOL> REASON_NO_REFERER = "<STR_LIT>" <EOL> REASON_BAD_REFERER = "<STR_LIT>" <EOL> REASON_NO_COOKIE = "<STR_LIT>" <EOL> REASON_NO_CSRF_COOKIE = "<STR_LIT>" <EOL> REASON_BAD_TOKEN = "<STR_LIT>" <EOL> def _get_failure_view ( ) : <EOL> """<STR_LIT>""" <EOL> return get_callable ( settings . CSRF_FAILURE_VIEW ) <EOL> def _get_new_csrf_key ( ) : <EOL> return md5_constructor ( "<STR_LIT>" <EOL> % ( randrange ( <NUM_LIT:0> , _MAX_CSRF_KEY ) , settings . SECRET_KEY ) ) . hexdigest ( ) <EOL> def _make_legacy_session_token ( session_id ) : <EOL> return md5_constructor ( settings . SECRET_KEY + session_id ) . hexdigest ( ) <EOL> def get_token ( request ) : <EOL> """<STR_LIT>""" <EOL> request . META [ "<STR_LIT>" ] = True <EOL> return request . META . get ( "<STR_LIT>" , None ) <EOL> def _sanitize_token ( token ) : <EOL> token = re . sub ( '<STR_LIT>' , '<STR_LIT>' , str ( token . decode ( '<STR_LIT:ascii>' , '<STR_LIT:ignore>' ) ) ) <EOL> if token == "<STR_LIT>" : <EOL> return _get_new_csrf_key ( ) <EOL> else : <EOL> return token <EOL> class CsrfViewMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def _accept ( self , request ) : <EOL> request . csrf_processing_done = True <EOL> return None <EOL> def _reject ( self , request , reason ) : <EOL> return _get_failure_view ( ) ( request , reason = reason ) <EOL> def process_view ( self , request , callback , callback_args , callback_kwargs ) : <EOL> if getattr ( request , '<STR_LIT>' , False ) : <EOL> return None <EOL> try : <EOL> request . META [ "<STR_LIT>" ] = _sanitize_token ( request . COOKIES [ settings . CSRF_COOKIE_NAME ] ) <EOL> cookie_is_new = False <EOL> except KeyError : <EOL> request . META [ "<STR_LIT>" ] = _get_new_csrf_key ( ) <EOL> cookie_is_new = True <EOL> if getattr ( callback , '<STR_LIT>' , False ) : <EOL> return None <EOL> if request . method == '<STR_LIT:POST>' : <EOL> if getattr ( request , '<STR_LIT>' , False ) : <EOL> return self . _accept ( request ) <EOL> if request . is_secure ( ) : <EOL> referer = request . META . get ( '<STR_LIT>' ) <EOL> if referer is None : <EOL> logger . warning ( '<STR_LIT>' % ( REASON_NO_REFERER , request . path ) , <EOL> extra = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : request , <EOL> } <EOL> ) <EOL> return self . _reject ( request , REASON_NO_REFERER ) <EOL> good_referer = '<STR_LIT>' % request . get_host ( ) <EOL> if not same_origin ( referer , good_referer ) : <EOL> reason = REASON_BAD_REFERER % ( referer , good_referer ) <EOL> logger . warning ( '<STR_LIT>' % ( reason , request . path ) , <EOL> extra = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : request , <EOL> } <EOL> ) <EOL> return self . _reject ( request , reason ) <EOL> if cookie_is_new : <EOL> try : <EOL> session_id = request . COOKIES [ settings . SESSION_COOKIE_NAME ] <EOL> csrf_token = _make_legacy_session_token ( session_id ) <EOL> except KeyError : <EOL> logger . warning ( '<STR_LIT>' % ( REASON_NO_COOKIE , request . path ) , <EOL> extra = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : request , <EOL> } <EOL> ) <EOL> return self . _reject ( request , REASON_NO_COOKIE ) <EOL> else : <EOL> csrf_token = request . META [ "<STR_LIT>" ] <EOL> request_csrf_token = request . POST . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if request_csrf_token == "<STR_LIT>" : <EOL> request_csrf_token = request . META . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if not constant_time_compare ( request_csrf_token , csrf_token ) : <EOL> if cookie_is_new : <EOL> logger . warning ( '<STR_LIT>' % ( REASON_NO_CSRF_COOKIE , request . path ) , <EOL> extra = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : request , <EOL> } <EOL> ) <EOL> return self . _reject ( request , REASON_NO_CSRF_COOKIE ) <EOL> else : <EOL> logger . warning ( '<STR_LIT>' % ( REASON_BAD_TOKEN , request . path ) , <EOL> extra = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : request , <EOL> } <EOL> ) <EOL> return self . _reject ( request , REASON_BAD_TOKEN ) <EOL> return self . _accept ( request ) <EOL> def process_response ( self , request , response ) : <EOL> if getattr ( response , '<STR_LIT>' , False ) : <EOL> return response <EOL> if request . META . get ( "<STR_LIT>" ) is None : <EOL> return response <EOL> if not request . META . get ( "<STR_LIT>" , False ) : <EOL> return response <EOL> response . set_cookie ( settings . CSRF_COOKIE_NAME , <EOL> request . META [ "<STR_LIT>" ] , max_age = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7> * <NUM_LIT> , <EOL> domain = settings . CSRF_COOKIE_DOMAIN ) <EOL> patch_vary_headers ( response , ( '<STR_LIT>' , ) ) <EOL> response . csrf_processing_done = True <EOL> return response <EOL> class CsrfResponseMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> import warnings <EOL> warnings . warn ( <EOL> "<STR_LIT>" , <EOL> DeprecationWarning <EOL> ) <EOL> def process_response ( self , request , response ) : <EOL> if getattr ( response , '<STR_LIT>' , False ) : <EOL> return response <EOL> if response [ '<STR_LIT:Content-Type>' ] . split ( '<STR_LIT:;>' ) [ <NUM_LIT:0> ] in _HTML_TYPES : <EOL> csrf_token = get_token ( request ) <EOL> if csrf_token is None : <EOL> return response <EOL> idattributes = itertools . chain ( ( "<STR_LIT>" , ) , <EOL> itertools . repeat ( '<STR_LIT>' ) ) <EOL> def add_csrf_field ( match ) : <EOL> """<STR_LIT>""" <EOL> return mark_safe ( match . group ( ) + "<STR_LIT>" + "<STR_LIT>" + idattributes . next ( ) + "<STR_LIT>" + csrf_token + "<STR_LIT>" ) <EOL> response . content , n = _POST_FORM_RE . subn ( add_csrf_field , response . content ) <EOL> if n > <NUM_LIT:0> : <EOL> patch_vary_headers ( response , ( '<STR_LIT>' , ) ) <EOL> del response [ '<STR_LIT>' ] <EOL> return response <EOL> class CsrfMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . response_middleware = CsrfResponseMiddleware ( ) <EOL> self . view_middleware = CsrfViewMiddleware ( ) <EOL> def process_response ( self , request , resp ) : <EOL> resp2 = self . response_middleware . process_response ( request , resp ) <EOL> return self . view_middleware . process_response ( request , resp2 ) <EOL> def process_view ( self , request , callback , callback_args , callback_kwargs ) : <EOL> return self . view_middleware . process_view ( request , callback , callback_args , <EOL> callback_kwargs ) </s>
|
<s> """<STR_LIT>""" <EOL> import hmac <EOL> from django . conf import settings <EOL> from django . utils . hashcompat import sha_constructor , sha_hmac <EOL> def salted_hmac ( key_salt , value , secret = None ) : <EOL> """<STR_LIT>""" <EOL> if secret is None : <EOL> secret = settings . SECRET_KEY <EOL> key = sha_constructor ( key_salt + secret ) . digest ( ) <EOL> return hmac . new ( key , msg = value , digestmod = sha_hmac ) <EOL> def constant_time_compare ( val1 , val2 ) : <EOL> """<STR_LIT>""" <EOL> if len ( val1 ) != len ( val2 ) : <EOL> return False <EOL> result = <NUM_LIT:0> <EOL> for x , y in zip ( val1 , val2 ) : <EOL> result |= ord ( x ) ^ ord ( y ) <EOL> return result == <NUM_LIT:0> </s>
|
<s> try : <EOL> from functools import wraps <EOL> except ImportError : <EOL> from django . utils . functional import wraps <EOL> from django . utils . decorators import decorator_from_middleware_with_args , available_attrs <EOL> from django . utils . cache import patch_cache_control , add_never_cache_headers <EOL> from django . middleware . cache import CacheMiddleware <EOL> def cache_page ( * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> cache_alias = kwargs . pop ( '<STR_LIT>' , None ) <EOL> key_prefix = kwargs . pop ( '<STR_LIT>' , None ) <EOL> assert not kwargs , "<STR_LIT>" <EOL> if len ( args ) > <NUM_LIT:1> : <EOL> assert len ( args ) == <NUM_LIT:2> , "<STR_LIT>" <EOL> if callable ( args [ <NUM_LIT:0> ] ) : <EOL> return decorator_from_middleware_with_args ( CacheMiddleware ) ( cache_timeout = args [ <NUM_LIT:1> ] , cache_alias = cache_alias , key_prefix = key_prefix ) ( args [ <NUM_LIT:0> ] ) <EOL> elif callable ( args [ <NUM_LIT:1> ] ) : <EOL> return decorator_from_middleware_with_args ( CacheMiddleware ) ( cache_timeout = args [ <NUM_LIT:0> ] , cache_alias = cache_alias , key_prefix = key_prefix ) ( args [ <NUM_LIT:1> ] ) <EOL> else : <EOL> assert False , "<STR_LIT>" <EOL> elif len ( args ) == <NUM_LIT:1> : <EOL> if callable ( args [ <NUM_LIT:0> ] ) : <EOL> return decorator_from_middleware_with_args ( CacheMiddleware ) ( cache_alias = cache_alias , key_prefix = key_prefix ) ( args [ <NUM_LIT:0> ] ) <EOL> else : <EOL> return decorator_from_middleware_with_args ( CacheMiddleware ) ( cache_timeout = args [ <NUM_LIT:0> ] , cache_alias = cache_alias , key_prefix = key_prefix ) <EOL> else : <EOL> return decorator_from_middleware_with_args ( CacheMiddleware ) ( cache_alias = cache_alias , key_prefix = key_prefix ) <EOL> def cache_control ( ** kwargs ) : <EOL> def _cache_controller ( viewfunc ) : <EOL> def _cache_controlled ( request , * args , ** kw ) : <EOL> response = viewfunc ( request , * args , ** kw ) <EOL> patch_cache_control ( response , ** kwargs ) <EOL> return response <EOL> return wraps ( viewfunc , assigned = available_attrs ( viewfunc ) ) ( _cache_controlled ) <EOL> return _cache_controller <EOL> def never_cache ( view_func ) : <EOL> """<STR_LIT>""" <EOL> def _wrapped_view_func ( request , * args , ** kwargs ) : <EOL> response = view_func ( request , * args , ** kwargs ) <EOL> add_never_cache_headers ( response ) <EOL> return response <EOL> return wraps ( view_func , assigned = available_attrs ( view_func ) ) ( _wrapped_view_func ) </s>
|
<s> import shutil <EOL> import sys <EOL> from django . core . cache import cache <EOL> from django . core . files . base import ContentFile <EOL> from django . core . files . uploadedfile import SimpleUploadedFile <EOL> from django . test import TestCase <EOL> from models import Storage , temp_storage , temp_storage_location <EOL> if sys . version_info >= ( <NUM_LIT:2> , <NUM_LIT:5> ) : <EOL> from tests_25 import FileObjTests <EOL> class FileTests ( TestCase ) : <EOL> def tearDown ( self ) : <EOL> shutil . rmtree ( temp_storage_location ) <EOL> def test_files ( self ) : <EOL> self . assertRaises ( AttributeError , lambda : Storage . normal ) <EOL> obj1 = Storage ( ) <EOL> self . assertEqual ( obj1 . normal . name , "<STR_LIT>" ) <EOL> self . assertRaises ( ValueError , lambda : obj1 . normal . size ) <EOL> obj1 . normal . save ( "<STR_LIT>" , ContentFile ( "<STR_LIT:content>" ) ) <EOL> self . assertEqual ( obj1 . normal . name , "<STR_LIT>" ) <EOL> self . assertEqual ( obj1 . normal . size , <NUM_LIT:7> ) <EOL> self . assertEqual ( obj1 . normal . read ( ) , "<STR_LIT:content>" ) <EOL> obj1 . normal . close ( ) <EOL> obj1 . normal = SimpleUploadedFile ( "<STR_LIT>" , "<STR_LIT:content>" ) <EOL> dirs , files = temp_storage . listdir ( "<STR_LIT>" ) <EOL> self . assertEqual ( dirs , [ ] ) <EOL> self . assertEqual ( sorted ( files ) , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> obj1 . save ( ) <EOL> dirs , files = temp_storage . listdir ( "<STR_LIT>" ) <EOL> self . assertEqual ( <EOL> sorted ( files ) , [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> ) <EOL> obj1 . normal . open ( ) <EOL> self . assertEqual ( obj1 . normal . read ( <NUM_LIT:3> ) , "<STR_LIT>" ) <EOL> self . assertEqual ( obj1 . normal . read ( ) , "<STR_LIT>" ) <EOL> self . assertEqual ( list ( obj1 . normal . chunks ( chunk_size = <NUM_LIT:2> ) ) , [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:t>" ] ) <EOL> obj1 . normal . close ( ) <EOL> obj2 = Storage ( ) <EOL> obj2 . normal . save ( "<STR_LIT>" , ContentFile ( "<STR_LIT>" ) ) <EOL> self . assertEqual ( obj2 . normal . name , "<STR_LIT>" ) <EOL> self . assertEqual ( obj2 . normal . size , <NUM_LIT:12> ) <EOL> cache . set ( "<STR_LIT>" , obj1 ) <EOL> cache . set ( "<STR_LIT>" , obj2 ) <EOL> self . assertEqual ( cache . get ( "<STR_LIT>" ) . normal . name , "<STR_LIT>" ) <EOL> obj2 . delete ( ) <EOL> obj2 . normal . save ( "<STR_LIT>" , ContentFile ( "<STR_LIT>" ) ) <EOL> self . assertEqual ( obj2 . normal . name , "<STR_LIT>" ) <EOL> objs = [ Storage ( ) for i in range ( <NUM_LIT:3> ) ] <EOL> for o in objs : <EOL> o . normal . save ( "<STR_LIT>" , ContentFile ( "<STR_LIT>" ) ) <EOL> self . assertEqual ( <EOL> [ o . normal . name for o in objs ] , <EOL> [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> ) <EOL> for o in objs : <EOL> o . delete ( ) <EOL> obj3 = Storage . objects . create ( ) <EOL> self . assertEqual ( obj3 . default . name , "<STR_LIT>" ) <EOL> self . assertEqual ( obj3 . default . read ( ) , "<STR_LIT>" ) <EOL> obj3 . default . close ( ) <EOL> obj3 . delete ( ) <EOL> obj3 = Storage ( ) <EOL> self . assertEqual ( obj3 . default . read ( ) , "<STR_LIT>" ) <EOL> obj3 . default . close ( ) <EOL> obj4 = Storage ( ) <EOL> obj4 . random . save ( "<STR_LIT>" , ContentFile ( "<STR_LIT>" ) ) <EOL> self . assertTrue ( obj4 . random . name . endswith ( "<STR_LIT>" ) ) <EOL> obj1 . normal . delete ( ) <EOL> obj2 . normal . delete ( ) <EOL> obj3 . default . delete ( ) <EOL> obj4 . random . delete ( ) </s>
|
<s> from datetime import datetime <EOL> from django . core . exceptions import ValidationError <EOL> from django . db import models <EOL> from django . test import TestCase <EOL> def validate_answer_to_universe ( value ) : <EOL> if value != <NUM_LIT> : <EOL> raise ValidationError ( '<STR_LIT>' , code = '<STR_LIT>' ) <EOL> class ModelToValidate ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> created = models . DateTimeField ( default = datetime . now ) <EOL> number = models . IntegerField ( db_column = '<STR_LIT>' ) <EOL> parent = models . ForeignKey ( '<STR_LIT>' , blank = True , null = True , limit_choices_to = { '<STR_LIT>' : <NUM_LIT:10> } ) <EOL> email = models . EmailField ( blank = True ) <EOL> url = models . URLField ( blank = True ) <EOL> url_verify = models . URLField ( blank = True , verify_exists = True ) <EOL> f_with_custom_validator = models . IntegerField ( blank = True , null = True , validators = [ validate_answer_to_universe ] ) <EOL> def clean ( self ) : <EOL> super ( ModelToValidate , self ) . clean ( ) <EOL> if self . number == <NUM_LIT:11> : <EOL> raise ValidationError ( '<STR_LIT>' ) <EOL> class UniqueFieldsModel ( models . Model ) : <EOL> unique_charfield = models . CharField ( max_length = <NUM_LIT:100> , unique = True ) <EOL> unique_integerfield = models . IntegerField ( unique = True ) <EOL> non_unique_field = models . IntegerField ( ) <EOL> class CustomPKModel ( models . Model ) : <EOL> my_pk_field = models . CharField ( max_length = <NUM_LIT:100> , primary_key = True ) <EOL> class UniqueTogetherModel ( models . Model ) : <EOL> cfield = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> ifield = models . IntegerField ( ) <EOL> efield = models . EmailField ( ) <EOL> class Meta : <EOL> unique_together = ( ( '<STR_LIT>' , '<STR_LIT>' , ) , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> class UniqueForDateModel ( models . Model ) : <EOL> start_date = models . DateField ( ) <EOL> end_date = models . DateTimeField ( ) <EOL> count = models . IntegerField ( unique_for_date = "<STR_LIT>" , unique_for_year = "<STR_LIT>" ) <EOL> order = models . IntegerField ( unique_for_month = "<STR_LIT>" ) <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> class CustomMessagesModel ( models . Model ) : <EOL> other = models . IntegerField ( blank = True , null = True ) <EOL> number = models . IntegerField ( db_column = '<STR_LIT>' , <EOL> error_messages = { '<STR_LIT:null>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> validators = [ validate_answer_to_universe ] <EOL> ) <EOL> class Author ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> class Article ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> author = models . ForeignKey ( Author ) <EOL> pub_date = models . DateTimeField ( blank = True ) <EOL> def clean ( self ) : <EOL> if self . pub_date is None : <EOL> self . pub_date = datetime . now ( ) <EOL> class Post ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:50> , unique_for_date = '<STR_LIT>' , blank = True ) <EOL> slug = models . CharField ( max_length = <NUM_LIT:50> , unique_for_year = '<STR_LIT>' , blank = True ) <EOL> subtitle = models . CharField ( max_length = <NUM_LIT:50> , unique_for_month = '<STR_LIT>' , blank = True ) <EOL> posted = models . DateField ( ) <EOL> def __unicode__ ( self ) : <EOL> return self . name <EOL> class FlexibleDatePost ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:50> , unique_for_date = '<STR_LIT>' , blank = True ) <EOL> slug = models . CharField ( max_length = <NUM_LIT:50> , unique_for_year = '<STR_LIT>' , blank = True ) <EOL> subtitle = models . CharField ( max_length = <NUM_LIT:50> , unique_for_month = '<STR_LIT>' , blank = True ) <EOL> posted = models . DateField ( blank = True , null = True ) </s>
|
<s> from django . contrib . contenttypes import generic <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . db import models <EOL> from django . db import connection <EOL> class Square ( models . Model ) : <EOL> root = models . IntegerField ( ) <EOL> square = models . PositiveIntegerField ( ) <EOL> def __unicode__ ( self ) : <EOL> return "<STR_LIT>" % ( self . root , self . square ) <EOL> class Person ( models . Model ) : <EOL> first_name = models . CharField ( max_length = <NUM_LIT:20> ) <EOL> last_name = models . CharField ( max_length = <NUM_LIT:20> ) <EOL> def __unicode__ ( self ) : <EOL> return u'<STR_LIT>' % ( self . first_name , self . last_name ) <EOL> class SchoolClass ( models . Model ) : <EOL> year = models . PositiveIntegerField ( ) <EOL> day = models . CharField ( max_length = <NUM_LIT:9> , blank = True ) <EOL> last_updated = models . DateTimeField ( ) <EOL> if connection . features . supports_long_model_names : <EOL> class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ( models . Model ) : <EOL> class Meta : <EOL> verbose_name = '<STR_LIT>' <EOL> primary_key_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models . AutoField ( primary_key = True ) <EOL> charfield_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models . ManyToManyField ( Person , blank = True ) <EOL> class Tag ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:30> ) <EOL> content_type = models . ForeignKey ( ContentType , related_name = '<STR_LIT>' ) <EOL> object_id = models . PositiveIntegerField ( ) <EOL> content_object = generic . GenericForeignKey ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class Post ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:30> ) <EOL> text = models . TextField ( ) <EOL> tags = generic . GenericRelation ( '<STR_LIT>' ) <EOL> class Meta : <EOL> db_table = '<STR_LIT>' <EOL> class Reporter ( models . Model ) : <EOL> first_name = models . CharField ( max_length = <NUM_LIT:30> ) <EOL> last_name = models . CharField ( max_length = <NUM_LIT:30> ) <EOL> def __unicode__ ( self ) : <EOL> return u"<STR_LIT>" % ( self . first_name , self . last_name ) <EOL> class Article ( models . Model ) : <EOL> headline = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> pub_date = models . DateField ( ) <EOL> reporter = models . ForeignKey ( Reporter ) <EOL> def __unicode__ ( self ) : <EOL> return self . headline </s>
|
<s> from django . core . exceptions import FieldError <EOL> from django . test import TestCase <EOL> from models import ( SelfRefer , Tag , TagCollection , Entry , SelfReferChild , <EOL> SelfReferChildSibling , Worksheet ) <EOL> class M2MRegressionTests ( TestCase ) : <EOL> def test_multiple_m2m ( self ) : <EOL> s1 = SelfRefer . objects . create ( name = '<STR_LIT>' ) <EOL> s2 = SelfRefer . objects . create ( name = '<STR_LIT>' ) <EOL> s3 = SelfRefer . objects . create ( name = '<STR_LIT>' ) <EOL> s1 . references . add ( s2 ) <EOL> s1 . related . add ( s3 ) <EOL> e1 = Entry . objects . create ( name = '<STR_LIT>' ) <EOL> t1 = Tag . objects . create ( name = '<STR_LIT>' ) <EOL> t2 = Tag . objects . create ( name = '<STR_LIT>' ) <EOL> e1 . topics . add ( t1 ) <EOL> e1 . related . add ( t2 ) <EOL> self . assertQuerysetEqual ( s1 . references . all ( ) , [ "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( s1 . related . all ( ) , [ "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( e1 . topics . all ( ) , [ "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( e1 . related . all ( ) , [ "<STR_LIT>" ] ) <EOL> def test_internal_related_name_not_in_error_msg ( self ) : <EOL> self . assertRaisesRegexp ( FieldError , <EOL> "<STR_LIT>" , <EOL> lambda : SelfRefer . objects . filter ( porcupine = '<STR_LIT>' ) <EOL> ) <EOL> def test_m2m_inheritance_symmetry ( self ) : <EOL> sr_child = SelfReferChild ( name = "<STR_LIT>" ) <EOL> sr_child . save ( ) <EOL> sr_sibling = SelfReferChildSibling ( name = "<STR_LIT>" ) <EOL> sr_sibling . save ( ) <EOL> sr_child . related . add ( sr_sibling ) <EOL> self . assertQuerysetEqual ( sr_child . related . all ( ) , [ "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( sr_sibling . related . all ( ) , [ "<STR_LIT>" ] ) <EOL> def test_m2m_pk_field_type ( self ) : <EOL> w = Worksheet ( id = '<STR_LIT:abc>' ) <EOL> w . save ( ) <EOL> w . delete ( ) <EOL> def test_add_m2m_with_base_class ( self ) : <EOL> t1 = Tag . objects . create ( name = '<STR_LIT>' ) <EOL> t2 = Tag . objects . create ( name = '<STR_LIT>' ) <EOL> c1 = TagCollection . objects . create ( name = '<STR_LIT>' ) <EOL> c1 . tags = [ t1 , t2 ] <EOL> c1 = TagCollection . objects . get ( name = '<STR_LIT>' ) <EOL> self . assertQuerysetEqual ( c1 . tags . all ( ) , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> self . assertQuerysetEqual ( t1 . tag_collections . all ( ) , [ "<STR_LIT>" ] ) </s>
|
<s> import time <EOL> from datetime import datetime , timedelta <EOL> from StringIO import StringIO <EOL> from django . conf import settings <EOL> from django . core . handlers . modpython import ModPythonRequest <EOL> from django . core . handlers . wsgi import WSGIRequest , LimitedStream <EOL> from django . http import HttpRequest , HttpResponse , parse_cookie <EOL> from django . utils import unittest <EOL> from django . utils . http import cookie_date <EOL> class RequestsTests ( unittest . TestCase ) : <EOL> def test_httprequest ( self ) : <EOL> request = HttpRequest ( ) <EOL> self . assertEqual ( request . GET . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . POST . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . COOKIES . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . META . keys ( ) , [ ] ) <EOL> def test_wsgirequest ( self ) : <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> self . assertEqual ( request . GET . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . POST . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . COOKIES . keys ( ) , [ ] ) <EOL> self . assertEqual ( set ( request . META . keys ( ) ) , set ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> self . assertEqual ( request . META [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> self . assertEqual ( request . META [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> self . assertEqual ( request . META [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> def test_modpythonrequest ( self ) : <EOL> class FakeModPythonRequest ( ModPythonRequest ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( FakeModPythonRequest , self ) . __init__ ( * args , ** kwargs ) <EOL> self . _get = self . _post = self . _meta = self . _cookies = { } <EOL> class Dummy : <EOL> def get_options ( self ) : <EOL> return { } <EOL> req = Dummy ( ) <EOL> req . uri = '<STR_LIT>' <EOL> request = FakeModPythonRequest ( req ) <EOL> self . assertEqual ( request . path , '<STR_LIT>' ) <EOL> self . assertEqual ( request . GET . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . POST . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . COOKIES . keys ( ) , [ ] ) <EOL> self . assertEqual ( request . META . keys ( ) , [ ] ) <EOL> def test_parse_cookie ( self ) : <EOL> self . assertEqual ( parse_cookie ( '<STR_LIT>' ) , { } ) <EOL> def test_httprequest_location ( self ) : <EOL> request = HttpRequest ( ) <EOL> self . assertEqual ( request . build_absolute_uri ( location = "<STR_LIT>" ) , <EOL> '<STR_LIT>' ) <EOL> request . get_host = lambda : '<STR_LIT>' <EOL> request . path = '<STR_LIT>' <EOL> self . assertEqual ( request . build_absolute_uri ( location = "<STR_LIT>" ) , <EOL> '<STR_LIT>' ) <EOL> def test_http_get_host ( self ) : <EOL> old_USE_X_FORWARDED_HOST = settings . USE_X_FORWARDED_HOST <EOL> try : <EOL> settings . USE_X_FORWARDED_HOST = False <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> finally : <EOL> settings . USE_X_FORWARDED_HOST = old_USE_X_FORWARDED_HOST <EOL> def test_http_get_host_with_x_forwarded_host ( self ) : <EOL> old_USE_X_FORWARDED_HOST = settings . USE_X_FORWARDED_HOST <EOL> try : <EOL> settings . USE_X_FORWARDED_HOST = True <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> request = HttpRequest ( ) <EOL> request . META = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> self . assertEqual ( request . get_host ( ) , '<STR_LIT>' ) <EOL> finally : <EOL> settings . USE_X_FORWARDED_HOST = old_USE_X_FORWARDED_HOST <EOL> def test_near_expiration ( self ) : <EOL> "<STR_LIT>" <EOL> response = HttpResponse ( ) <EOL> expires = datetime . utcnow ( ) + timedelta ( seconds = <NUM_LIT:10> ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> response . set_cookie ( '<STR_LIT>' , expires = expires ) <EOL> datetime_cookie = response . cookies [ '<STR_LIT>' ] <EOL> self . assertEqual ( datetime_cookie [ '<STR_LIT>' ] , <NUM_LIT:10> ) <EOL> def test_far_expiration ( self ) : <EOL> "<STR_LIT>" <EOL> response = HttpResponse ( ) <EOL> response . set_cookie ( '<STR_LIT>' , expires = datetime ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> ) ) <EOL> datetime_cookie = response . cookies [ '<STR_LIT>' ] <EOL> self . assertEqual ( datetime_cookie [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> def test_max_age_expiration ( self ) : <EOL> "<STR_LIT>" <EOL> response = HttpResponse ( ) <EOL> response . set_cookie ( '<STR_LIT>' , max_age = <NUM_LIT:10> ) <EOL> max_age_cookie = response . cookies [ '<STR_LIT>' ] <EOL> self . assertEqual ( max_age_cookie [ '<STR_LIT>' ] , <NUM_LIT:10> ) <EOL> self . assertEqual ( max_age_cookie [ '<STR_LIT>' ] , cookie_date ( time . time ( ) + <NUM_LIT:10> ) ) <EOL> def test_httponly_cookie ( self ) : <EOL> response = HttpResponse ( ) <EOL> response . set_cookie ( '<STR_LIT>' , httponly = True ) <EOL> example_cookie = response . cookies [ '<STR_LIT>' ] <EOL> self . assertTrue ( '<STR_LIT>' in str ( example_cookie ) ) <EOL> self . assertTrue ( example_cookie [ '<STR_LIT>' ] ) <EOL> def test_limited_stream ( self ) : <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT:test>' ) , <NUM_LIT:2> ) <EOL> self . assertEqual ( stream . read ( ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . read ( ) , '<STR_LIT>' ) <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT:test>' ) , <NUM_LIT:2> ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:5> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:5> ) , '<STR_LIT>' ) <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT>' ) , <NUM_LIT:8> ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:5> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:5> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:5> ) , '<STR_LIT>' ) <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT>' ) , <NUM_LIT> ) <EOL> self . assertEqual ( stream . readline ( ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:2> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:6> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:4> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( ) , '<STR_LIT:\n>' ) <EOL> self . assertEqual ( stream . readline ( ) , '<STR_LIT>' ) <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT>' ) , <NUM_LIT:9> ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:10> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:3> ) , '<STR_LIT:abc>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:3> ) , '<STR_LIT:d>' ) <EOL> self . assertEqual ( stream . readline ( <NUM_LIT:2> ) , '<STR_LIT>' ) <EOL> stream = LimitedStream ( StringIO ( '<STR_LIT>' ) , <NUM_LIT:9> ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:6> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:2> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:2> ) , '<STR_LIT:d>' ) <EOL> self . assertEqual ( stream . read ( <NUM_LIT:2> ) , '<STR_LIT>' ) <EOL> self . assertEqual ( stream . read ( ) , '<STR_LIT>' ) <EOL> def test_stream ( self ) : <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> self . assertEqual ( request . read ( ) , '<STR_LIT>' ) <EOL> def test_read_after_value ( self ) : <EOL> """<STR_LIT>""" <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> self . assertEqual ( request . POST , { u'<STR_LIT:name>' : [ u'<STR_LIT:value>' ] } ) <EOL> self . assertEqual ( request . raw_post_data , '<STR_LIT>' ) <EOL> self . assertEqual ( request . read ( ) , '<STR_LIT>' ) <EOL> def test_value_after_read ( self ) : <EOL> """<STR_LIT>""" <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> self . assertEqual ( request . read ( <NUM_LIT:2> ) , '<STR_LIT>' ) <EOL> self . assertRaises ( Exception , lambda : request . raw_post_data ) <EOL> self . assertEqual ( request . POST , { } ) <EOL> def test_raw_post_data_after_POST_multipart ( self ) : <EOL> """<STR_LIT>""" <EOL> payload = "<STR_LIT:\r\n>" . join ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:value>' , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ] ) <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : len ( payload ) , <EOL> '<STR_LIT>' : StringIO ( payload ) } ) <EOL> self . assertEqual ( request . POST , { u'<STR_LIT:name>' : [ u'<STR_LIT:value>' ] } ) <EOL> self . assertRaises ( Exception , lambda : request . raw_post_data ) <EOL> def test_POST_multipart_with_content_length_zero ( self ) : <EOL> """<STR_LIT>""" <EOL> payload = "<STR_LIT:\r\n>" . join ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:value>' , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ] ) <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT:0> , <EOL> '<STR_LIT>' : StringIO ( payload ) } ) <EOL> self . assertEqual ( request . POST , { } ) <EOL> def test_read_by_lines ( self ) : <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> self . assertEqual ( list ( request ) , [ '<STR_LIT>' ] ) <EOL> def test_POST_after_raw_post_data_read ( self ) : <EOL> """<STR_LIT>""" <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> raw_data = request . raw_post_data <EOL> self . assertEqual ( request . POST , { u'<STR_LIT:name>' : [ u'<STR_LIT:value>' ] } ) <EOL> def test_POST_after_raw_post_data_read_and_stream_read ( self ) : <EOL> """<STR_LIT>""" <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , '<STR_LIT>' : StringIO ( '<STR_LIT>' ) } ) <EOL> raw_data = request . raw_post_data <EOL> self . assertEqual ( request . read ( <NUM_LIT:1> ) , u'<STR_LIT:n>' ) <EOL> self . assertEqual ( request . POST , { u'<STR_LIT:name>' : [ u'<STR_LIT:value>' ] } ) <EOL> def test_POST_after_raw_post_data_read_and_stream_read_multipart ( self ) : <EOL> """<STR_LIT>""" <EOL> payload = "<STR_LIT:\r\n>" . join ( [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT:value>' , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ] ) <EOL> request = WSGIRequest ( { '<STR_LIT>' : '<STR_LIT:POST>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : len ( payload ) , <EOL> '<STR_LIT>' : StringIO ( payload ) } ) <EOL> raw_data = request . raw_post_data <EOL> self . assertEqual ( request . read ( <NUM_LIT> ) , u'<STR_LIT>' ) <EOL> self . assertEqual ( request . POST , { u'<STR_LIT:name>' : [ u'<STR_LIT:value>' ] } ) </s>
|
<s> from django import template <EOL> from django . template . defaultfilters import stringfilter <EOL> register = template . Library ( ) <EOL> def trim ( value , num ) : <EOL> return value [ : num ] <EOL> trim = stringfilter ( trim ) <EOL> register . filter ( trim ) <EOL> @ register . simple_tag <EOL> def no_params ( ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" <EOL> no_params . anything = "<STR_LIT>" <EOL> @ register . simple_tag <EOL> def one_param ( arg ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % arg <EOL> one_param . anything = "<STR_LIT>" <EOL> @ register . simple_tag ( takes_context = False ) <EOL> def explicit_no_context ( arg ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % arg <EOL> explicit_no_context . anything = "<STR_LIT>" <EOL> @ register . simple_tag ( takes_context = True ) <EOL> def no_params_with_context ( context ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % context [ '<STR_LIT:value>' ] <EOL> no_params_with_context . anything = "<STR_LIT>" <EOL> @ register . simple_tag ( takes_context = True ) <EOL> def params_and_context ( context , arg ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % ( context [ '<STR_LIT:value>' ] , arg ) <EOL> params_and_context . anything = "<STR_LIT>" <EOL> @ register . inclusion_tag ( '<STR_LIT>' ) <EOL> def inclusion_no_params ( ) : <EOL> """<STR_LIT>""" <EOL> return { "<STR_LIT:result>" : "<STR_LIT>" } <EOL> inclusion_no_params . anything = "<STR_LIT>" <EOL> @ register . inclusion_tag ( '<STR_LIT>' ) <EOL> def inclusion_one_param ( arg ) : <EOL> """<STR_LIT>""" <EOL> return { "<STR_LIT:result>" : "<STR_LIT>" % arg } <EOL> inclusion_one_param . anything = "<STR_LIT>" <EOL> @ register . inclusion_tag ( '<STR_LIT>' , takes_context = False ) <EOL> def inclusion_explicit_no_context ( arg ) : <EOL> """<STR_LIT>""" <EOL> return { "<STR_LIT:result>" : "<STR_LIT>" % arg } <EOL> inclusion_explicit_no_context . anything = "<STR_LIT>" <EOL> @ register . inclusion_tag ( '<STR_LIT>' , takes_context = True ) <EOL> def inclusion_no_params_with_context ( context ) : <EOL> """<STR_LIT>""" <EOL> return { "<STR_LIT:result>" : "<STR_LIT>" % context [ '<STR_LIT:value>' ] } <EOL> inclusion_no_params_with_context . anything = "<STR_LIT>" <EOL> @ register . inclusion_tag ( '<STR_LIT>' , takes_context = True ) <EOL> def inclusion_params_and_context ( context , arg ) : <EOL> """<STR_LIT>""" <EOL> return { "<STR_LIT:result>" : "<STR_LIT>" % ( context [ '<STR_LIT:value>' ] , arg ) } <EOL> inclusion_params_and_context . anything = "<STR_LIT>" </s>
|
<s> from django . http import HttpResponse <EOL> from django . middleware . doc import XViewMiddleware <EOL> from django . template import Template , Context <EOL> from django . template . response import TemplateResponse <EOL> from django . test import TestCase , RequestFactory <EOL> from django . utils . decorators import decorator_from_middleware <EOL> xview_dec = decorator_from_middleware ( XViewMiddleware ) <EOL> @ xview_dec <EOL> def xview ( request ) : <EOL> return HttpResponse ( ) <EOL> class ClassXView ( object ) : <EOL> def __call__ ( self , request ) : <EOL> return HttpResponse ( ) <EOL> class_xview = xview_dec ( ClassXView ( ) ) <EOL> class FullMiddleware ( object ) : <EOL> def process_request ( self , request ) : <EOL> request . process_request_reached = True <EOL> def process_view ( sef , request , view_func , view_args , view_kwargs ) : <EOL> request . process_view_reached = True <EOL> def process_template_response ( self , request , response ) : <EOL> request . process_template_response_reached = True <EOL> return response <EOL> def process_response ( self , request , response ) : <EOL> request . process_response_content = response . content <EOL> request . process_response_reached = True <EOL> return response <EOL> full_dec = decorator_from_middleware ( FullMiddleware ) <EOL> class DecoratorFromMiddlewareTests ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> rf = RequestFactory ( ) <EOL> def test_process_view_middleware ( self ) : <EOL> """<STR_LIT>""" <EOL> xview ( self . rf . get ( '<STR_LIT:/>' ) ) <EOL> def test_callable_process_view_middleware ( self ) : <EOL> """<STR_LIT>""" <EOL> class_xview ( self . rf . get ( '<STR_LIT:/>' ) ) <EOL> def test_full_dec_normal ( self ) : <EOL> """<STR_LIT>""" <EOL> @ full_dec <EOL> def normal_view ( request ) : <EOL> t = Template ( "<STR_LIT>" ) <EOL> return HttpResponse ( t . render ( Context ( { } ) ) ) <EOL> request = self . rf . get ( '<STR_LIT:/>' ) <EOL> response = normal_view ( request ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertFalse ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> def test_full_dec_templateresponse ( self ) : <EOL> """<STR_LIT>""" <EOL> @ full_dec <EOL> def template_response_view ( request ) : <EOL> t = Template ( "<STR_LIT>" ) <EOL> return TemplateResponse ( request , t , { } ) <EOL> request = self . rf . get ( '<STR_LIT:/>' ) <EOL> response = template_response_view ( request ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertFalse ( response . _is_rendered ) <EOL> self . assertFalse ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> response . render ( ) <EOL> self . assertTrue ( getattr ( request , '<STR_LIT>' , False ) ) <EOL> self . assertEqual ( request . process_response_content , "<STR_LIT>" ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . core . exceptions import PermissionDenied <EOL> from django . contrib . admin import helpers <EOL> from django . contrib . admin . util import get_deleted_objects , model_ngettext <EOL> from django . db import router <EOL> from django . template . response import TemplateResponse <EOL> from django . utils . encoding import force_unicode <EOL> from django . utils . translation import ugettext_lazy , ugettext as _ <EOL> def delete_selected ( modeladmin , request , queryset ) : <EOL> """<STR_LIT>""" <EOL> opts = modeladmin . model . _meta <EOL> app_label = opts . app_label <EOL> if not modeladmin . has_delete_permission ( request ) : <EOL> raise PermissionDenied <EOL> using = router . db_for_write ( modeladmin . model ) <EOL> deletable_objects , perms_needed , protected = get_deleted_objects ( <EOL> queryset , opts , request . user , modeladmin . admin_site , using ) <EOL> if request . POST . get ( '<STR_LIT>' ) : <EOL> if perms_needed : <EOL> raise PermissionDenied <EOL> n = queryset . count ( ) <EOL> if n : <EOL> for obj in queryset : <EOL> obj_display = force_unicode ( obj ) <EOL> modeladmin . log_deletion ( request , obj , obj_display ) <EOL> queryset . delete ( ) <EOL> modeladmin . message_user ( request , _ ( "<STR_LIT>" ) % { <EOL> "<STR_LIT:count>" : n , "<STR_LIT>" : model_ngettext ( modeladmin . opts , n ) <EOL> } ) <EOL> return None <EOL> if len ( queryset ) == <NUM_LIT:1> : <EOL> objects_name = force_unicode ( opts . verbose_name ) <EOL> else : <EOL> objects_name = force_unicode ( opts . verbose_name_plural ) <EOL> if perms_needed or protected : <EOL> title = _ ( "<STR_LIT>" ) % { "<STR_LIT:name>" : objects_name } <EOL> else : <EOL> title = _ ( "<STR_LIT>" ) <EOL> context = { <EOL> "<STR_LIT:title>" : title , <EOL> "<STR_LIT>" : objects_name , <EOL> "<STR_LIT>" : [ deletable_objects ] , <EOL> '<STR_LIT>' : queryset , <EOL> "<STR_LIT>" : perms_needed , <EOL> "<STR_LIT>" : protected , <EOL> "<STR_LIT>" : opts , <EOL> "<STR_LIT>" : app_label , <EOL> '<STR_LIT>' : helpers . ACTION_CHECKBOX_NAME , <EOL> } <EOL> return TemplateResponse ( request , modeladmin . delete_selected_confirmation_template or [ <EOL> "<STR_LIT>" % ( app_label , opts . object_name . lower ( ) ) , <EOL> "<STR_LIT>" % app_label , <EOL> "<STR_LIT>" <EOL> ] , context , current_app = modeladmin . admin_site . name ) <EOL> delete_selected . short_description = ugettext_lazy ( "<STR_LIT>" ) </s>
|
<s> import hashlib <EOL> from django . conf import settings <EOL> from django . utils import importlib <EOL> from django . utils . datastructures import SortedDict <EOL> from django . utils . encoding import smart_str <EOL> from django . core . exceptions import ImproperlyConfigured <EOL> from django . utils . crypto import ( <EOL> pbkdf2 , constant_time_compare , get_random_string ) <EOL> from django . utils . translation import ugettext_noop as _ <EOL> UNUSABLE_PASSWORD = '<STR_LIT:!>' <EOL> HASHERS = None <EOL> PREFERRED_HASHER = None <EOL> def is_password_usable ( encoded ) : <EOL> return ( encoded is not None and encoded != UNUSABLE_PASSWORD ) <EOL> def check_password ( password , encoded , setter = None , preferred = '<STR_LIT:default>' ) : <EOL> """<STR_LIT>""" <EOL> if not password or not is_password_usable ( encoded ) : <EOL> return False <EOL> preferred = get_hasher ( preferred ) <EOL> raw_password = password <EOL> password = smart_str ( password ) <EOL> encoded = smart_str ( encoded ) <EOL> if len ( encoded ) == <NUM_LIT:32> and '<STR_LIT:$>' not in encoded : <EOL> hasher = get_hasher ( '<STR_LIT>' ) <EOL> else : <EOL> algorithm = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> hasher = get_hasher ( algorithm ) <EOL> must_update = hasher . algorithm != preferred . algorithm <EOL> is_correct = hasher . verify ( password , encoded ) <EOL> if setter and is_correct and must_update : <EOL> setter ( raw_password ) <EOL> return is_correct <EOL> def make_password ( password , salt = None , hasher = '<STR_LIT:default>' ) : <EOL> """<STR_LIT>""" <EOL> if not password : <EOL> return UNUSABLE_PASSWORD <EOL> hasher = get_hasher ( hasher ) <EOL> password = smart_str ( password ) <EOL> if not salt : <EOL> salt = hasher . salt ( ) <EOL> salt = smart_str ( salt ) <EOL> return hasher . encode ( password , salt ) <EOL> def load_hashers ( password_hashers = None ) : <EOL> global HASHERS <EOL> global PREFERRED_HASHER <EOL> hashers = [ ] <EOL> if not password_hashers : <EOL> password_hashers = settings . PASSWORD_HASHERS <EOL> for backend in password_hashers : <EOL> try : <EOL> mod_path , cls_name = backend . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> mod = importlib . import_module ( mod_path ) <EOL> hasher_cls = getattr ( mod , cls_name ) <EOL> except ( AttributeError , ImportError , ValueError ) : <EOL> raise ImproperlyConfigured ( "<STR_LIT>" % backend ) <EOL> hasher = hasher_cls ( ) <EOL> if not getattr ( hasher , '<STR_LIT>' ) : <EOL> raise ImproperlyConfigured ( "<STR_LIT>" <EOL> "<STR_LIT>" % backend ) <EOL> hashers . append ( hasher ) <EOL> HASHERS = dict ( [ ( hasher . algorithm , hasher ) for hasher in hashers ] ) <EOL> PREFERRED_HASHER = hashers [ <NUM_LIT:0> ] <EOL> def get_hasher ( algorithm = '<STR_LIT:default>' ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( algorithm , '<STR_LIT>' ) : <EOL> return algorithm <EOL> elif algorithm == '<STR_LIT:default>' : <EOL> if PREFERRED_HASHER is None : <EOL> load_hashers ( ) <EOL> return PREFERRED_HASHER <EOL> else : <EOL> if HASHERS is None : <EOL> load_hashers ( ) <EOL> if algorithm not in HASHERS : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % algorithm ) <EOL> return HASHERS [ algorithm ] <EOL> def mask_hash ( hash , show = <NUM_LIT:6> , char = "<STR_LIT:*>" ) : <EOL> """<STR_LIT>""" <EOL> masked = hash [ : show ] <EOL> masked += char * len ( hash [ show : ] ) <EOL> return masked <EOL> class BasePasswordHasher ( object ) : <EOL> """<STR_LIT>""" <EOL> algorithm = None <EOL> library = None <EOL> def _load_library ( self ) : <EOL> if self . library is not None : <EOL> if isinstance ( self . library , ( tuple , list ) ) : <EOL> name , mod_path = self . library <EOL> else : <EOL> name = mod_path = self . library <EOL> try : <EOL> module = importlib . import_module ( mod_path ) <EOL> except ImportError : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" % name ) <EOL> return module <EOL> raise ValueError ( "<STR_LIT>" % <EOL> self . __class__ ) <EOL> def salt ( self ) : <EOL> """<STR_LIT>""" <EOL> return get_random_string ( ) <EOL> def verify ( self , password , encoded ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def encode ( self , password , salt ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def safe_summary ( self , encoded ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> class PBKDF2PasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> iterations = <NUM_LIT> <EOL> digest = hashlib . sha256 <EOL> def encode ( self , password , salt , iterations = None ) : <EOL> assert password <EOL> assert salt and '<STR_LIT:$>' not in salt <EOL> if not iterations : <EOL> iterations = self . iterations <EOL> hash = pbkdf2 ( password , salt , iterations , digest = self . digest ) <EOL> hash = hash . encode ( '<STR_LIT>' ) . strip ( ) <EOL> return "<STR_LIT>" % ( self . algorithm , iterations , salt , hash ) <EOL> def verify ( self , password , encoded ) : <EOL> algorithm , iterations , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:3> ) <EOL> assert algorithm == self . algorithm <EOL> encoded_2 = self . encode ( password , salt , int ( iterations ) ) <EOL> return constant_time_compare ( encoded , encoded_2 ) <EOL> def safe_summary ( self , encoded ) : <EOL> algorithm , iterations , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:3> ) <EOL> assert algorithm == self . algorithm <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , iterations ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( salt ) ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( hash ) ) , <EOL> ] ) <EOL> class PBKDF2SHA1PasswordHasher ( PBKDF2PasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> digest = hashlib . sha1 <EOL> class BCryptPasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> library = ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> rounds = <NUM_LIT:12> <EOL> def salt ( self ) : <EOL> bcrypt = self . _load_library ( ) <EOL> return bcrypt . gensalt ( self . rounds ) <EOL> def encode ( self , password , salt ) : <EOL> bcrypt = self . _load_library ( ) <EOL> data = bcrypt . hashpw ( password , salt ) <EOL> return "<STR_LIT>" % ( self . algorithm , data ) <EOL> def verify ( self , password , encoded ) : <EOL> algorithm , data = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:1> ) <EOL> assert algorithm == self . algorithm <EOL> bcrypt = self . _load_library ( ) <EOL> return constant_time_compare ( data , bcrypt . hashpw ( password , data ) ) <EOL> def safe_summary ( self , encoded ) : <EOL> algorithm , empty , algostr , work_factor , data = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:4> ) <EOL> assert algorithm == self . algorithm <EOL> salt , checksum = data [ : <NUM_LIT> ] , data [ <NUM_LIT> : ] <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , work_factor ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( salt ) ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( checksum ) ) , <EOL> ] ) <EOL> class SHA1PasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> def encode ( self , password , salt ) : <EOL> assert password <EOL> assert salt and '<STR_LIT:$>' not in salt <EOL> hash = hashlib . sha1 ( salt + password ) . hexdigest ( ) <EOL> return "<STR_LIT>" % ( self . algorithm , salt , hash ) <EOL> def verify ( self , password , encoded ) : <EOL> algorithm , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> encoded_2 = self . encode ( password , salt ) <EOL> return constant_time_compare ( encoded , encoded_2 ) <EOL> def safe_summary ( self , encoded ) : <EOL> algorithm , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( salt , show = <NUM_LIT:2> ) ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( hash ) ) , <EOL> ] ) <EOL> class MD5PasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> def encode ( self , password , salt ) : <EOL> assert password <EOL> assert salt and '<STR_LIT:$>' not in salt <EOL> hash = hashlib . md5 ( salt + password ) . hexdigest ( ) <EOL> return "<STR_LIT>" % ( self . algorithm , salt , hash ) <EOL> def verify ( self , password , encoded ) : <EOL> algorithm , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> encoded_2 = self . encode ( password , salt ) <EOL> return constant_time_compare ( encoded , encoded_2 ) <EOL> def safe_summary ( self , encoded ) : <EOL> algorithm , salt , hash = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( salt , show = <NUM_LIT:2> ) ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( hash ) ) , <EOL> ] ) <EOL> class UnsaltedMD5PasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> def salt ( self ) : <EOL> return '<STR_LIT>' <EOL> def encode ( self , password , salt ) : <EOL> return hashlib . md5 ( password ) . hexdigest ( ) <EOL> def verify ( self , password , encoded ) : <EOL> encoded_2 = self . encode ( password , '<STR_LIT>' ) <EOL> return constant_time_compare ( encoded , encoded_2 ) <EOL> def safe_summary ( self , encoded ) : <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , self . algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( encoded , show = <NUM_LIT:3> ) ) , <EOL> ] ) <EOL> class CryptPasswordHasher ( BasePasswordHasher ) : <EOL> """<STR_LIT>""" <EOL> algorithm = "<STR_LIT>" <EOL> library = "<STR_LIT>" <EOL> def salt ( self ) : <EOL> return get_random_string ( <NUM_LIT:2> ) <EOL> def encode ( self , password , salt ) : <EOL> crypt = self . _load_library ( ) <EOL> assert len ( salt ) == <NUM_LIT:2> <EOL> data = crypt . crypt ( password , salt ) <EOL> return "<STR_LIT>" % ( self . algorithm , '<STR_LIT>' , data ) <EOL> def verify ( self , password , encoded ) : <EOL> crypt = self . _load_library ( ) <EOL> algorithm , salt , data = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> return constant_time_compare ( data , crypt . crypt ( password , data ) ) <EOL> def safe_summary ( self , encoded ) : <EOL> algorithm , salt , data = encoded . split ( '<STR_LIT:$>' , <NUM_LIT:2> ) <EOL> assert algorithm == self . algorithm <EOL> return SortedDict ( [ <EOL> ( _ ( '<STR_LIT>' ) , algorithm ) , <EOL> ( _ ( '<STR_LIT>' ) , salt ) , <EOL> ( _ ( '<STR_LIT>' ) , mask_hash ( data , show = <NUM_LIT:3> ) ) , <EOL> ] ) </s>
|
<s> from __future__ import absolute_import <EOL> from django import http <EOL> from django . conf import settings <EOL> from django . contrib import comments <EOL> from django . contrib . comments import signals <EOL> from django . contrib . comments . views . utils import next_redirect , confirmation_view <EOL> from django . core . exceptions import ObjectDoesNotExist , ValidationError <EOL> from django . db import models <EOL> from django . shortcuts import render_to_response <EOL> from django . template import RequestContext <EOL> from django . template . loader import render_to_string <EOL> from django . utils . html import escape <EOL> from django . views . decorators . csrf import csrf_protect <EOL> from django . views . decorators . http import require_POST <EOL> class CommentPostBadRequest ( http . HttpResponseBadRequest ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , why ) : <EOL> super ( CommentPostBadRequest , self ) . __init__ ( ) <EOL> if settings . DEBUG : <EOL> self . content = render_to_string ( "<STR_LIT>" , { "<STR_LIT>" : why } ) <EOL> @ csrf_protect <EOL> @ require_POST <EOL> def post_comment ( request , next = None , using = None ) : <EOL> """<STR_LIT>""" <EOL> data = request . POST . copy ( ) <EOL> if request . user . is_authenticated ( ) : <EOL> if not data . get ( '<STR_LIT:name>' , '<STR_LIT>' ) : <EOL> data [ "<STR_LIT:name>" ] = request . user . get_full_name ( ) or request . user . username <EOL> if not data . get ( '<STR_LIT:email>' , '<STR_LIT>' ) : <EOL> data [ "<STR_LIT:email>" ] = request . user . email <EOL> ctype = data . get ( "<STR_LIT>" ) <EOL> object_pk = data . get ( "<STR_LIT>" ) <EOL> if ctype is None or object_pk is None : <EOL> return CommentPostBadRequest ( "<STR_LIT>" ) <EOL> try : <EOL> model = models . get_model ( * ctype . split ( "<STR_LIT:.>" , <NUM_LIT:1> ) ) <EOL> target = model . _default_manager . using ( using ) . get ( pk = object_pk ) <EOL> except TypeError : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % escape ( ctype ) ) <EOL> except AttributeError : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % escape ( ctype ) ) <EOL> except ObjectDoesNotExist : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % ( escape ( ctype ) , escape ( object_pk ) ) ) <EOL> except ( ValueError , ValidationError ) , e : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % ( escape ( ctype ) , escape ( object_pk ) , e . __class__ . __name__ ) ) <EOL> preview = "<STR_LIT>" in data <EOL> form = comments . get_form ( ) ( target , data = data ) <EOL> if form . security_errors ( ) : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % escape ( str ( form . security_errors ( ) ) ) ) <EOL> if form . errors or preview : <EOL> template_list = [ <EOL> "<STR_LIT>" % ( model . _meta . app_label , model . _meta . module_name ) , <EOL> "<STR_LIT>" % model . _meta . app_label , <EOL> "<STR_LIT>" % ( model . _meta . app_label , model . _meta . module_name ) , <EOL> "<STR_LIT>" % model . _meta . app_label , <EOL> "<STR_LIT>" , <EOL> ] <EOL> return render_to_response ( <EOL> template_list , { <EOL> "<STR_LIT>" : form . data . get ( "<STR_LIT>" , "<STR_LIT>" ) , <EOL> "<STR_LIT>" : form , <EOL> "<STR_LIT>" : data . get ( "<STR_LIT>" , next ) , <EOL> } , <EOL> RequestContext ( request , { } ) <EOL> ) <EOL> comment = form . get_comment_object ( ) <EOL> comment . ip_address = request . META . get ( "<STR_LIT>" , None ) <EOL> if request . user . is_authenticated ( ) : <EOL> comment . user = request . user <EOL> responses = signals . comment_will_be_posted . send ( <EOL> sender = comment . __class__ , <EOL> comment = comment , <EOL> request = request <EOL> ) <EOL> for ( receiver , response ) in responses : <EOL> if response == False : <EOL> return CommentPostBadRequest ( <EOL> "<STR_LIT>" % receiver . __name__ ) <EOL> comment . save ( ) <EOL> signals . comment_was_posted . send ( <EOL> sender = comment . __class__ , <EOL> comment = comment , <EOL> request = request <EOL> ) <EOL> return next_redirect ( request , next , comment_done , c = comment . _get_pk_val ( ) ) <EOL> comment_done = confirmation_view ( <EOL> template = "<STR_LIT>" , <EOL> doc = """<STR_LIT>""" <EOL> ) </s>
|
<s> from django . test import TestCase <EOL> from django . core import signing <EOL> from django . core . exceptions import SuspiciousOperation <EOL> from django . http import HttpResponse <EOL> from django . contrib . formtools . wizard . storage . cookie import CookieStorage <EOL> from django . contrib . formtools . tests . wizard . storage import get_request , TestStorage <EOL> class TestCookieStorage ( TestStorage , TestCase ) : <EOL> def get_storage ( self ) : <EOL> return CookieStorage <EOL> def test_manipulated_cookie ( self ) : <EOL> request = get_request ( ) <EOL> storage = self . get_storage ( ) ( '<STR_LIT>' , request , None ) <EOL> cookie_signer = signing . get_cookie_signer ( storage . prefix ) <EOL> storage . request . COOKIES [ storage . prefix ] = cookie_signer . sign ( <EOL> storage . encoder . encode ( { '<STR_LIT>' : '<STR_LIT>' } ) ) <EOL> self . assertEqual ( storage . load_data ( ) , { '<STR_LIT>' : '<STR_LIT>' } ) <EOL> storage . request . COOKIES [ storage . prefix ] = '<STR_LIT>' <EOL> self . assertRaises ( SuspiciousOperation , storage . load_data ) <EOL> def test_reset_cookie ( self ) : <EOL> request = get_request ( ) <EOL> storage = self . get_storage ( ) ( '<STR_LIT>' , request , None ) <EOL> storage . data = { '<STR_LIT>' : '<STR_LIT>' } <EOL> response = HttpResponse ( ) <EOL> storage . update_response ( response ) <EOL> cookie_signer = signing . get_cookie_signer ( storage . prefix ) <EOL> signed_cookie_data = cookie_signer . sign ( storage . encoder . encode ( storage . data ) ) <EOL> self . assertEqual ( response . cookies [ storage . prefix ] . value , signed_cookie_data ) <EOL> storage . init_data ( ) <EOL> storage . update_response ( response ) <EOL> unsigned_cookie_data = cookie_signer . unsign ( response . cookies [ storage . prefix ] . value ) <EOL> self . assertEqual ( unsigned_cookie_data , '<STR_LIT>' ) </s>
|
<s> from django . contrib . gis . db . models . sql . compiler import GeoSQLCompiler as BaseGeoSQLCompiler <EOL> from django . db . backends . oracle import compiler <EOL> SQLCompiler = compiler . SQLCompiler <EOL> class GeoSQLCompiler ( BaseGeoSQLCompiler , SQLCompiler ) : <EOL> pass <EOL> class SQLInsertCompiler ( compiler . SQLInsertCompiler , GeoSQLCompiler ) : <EOL> pass <EOL> class SQLDeleteCompiler ( compiler . SQLDeleteCompiler , GeoSQLCompiler ) : <EOL> pass <EOL> class SQLUpdateCompiler ( compiler . SQLUpdateCompiler , GeoSQLCompiler ) : <EOL> pass <EOL> class SQLAggregateCompiler ( compiler . SQLAggregateCompiler , GeoSQLCompiler ) : <EOL> pass <EOL> class SQLDateCompiler ( compiler . SQLDateCompiler , GeoSQLCompiler ) : <EOL> pass </s>
|
<s> from ctypes import c_char_p , c_float , c_int , string_at , Structure , POINTER <EOL> from django . contrib . gis . geoip . libgeoip import lgeoip , free <EOL> class GeoIPRecord ( Structure ) : <EOL> _fields_ = [ ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ( '<STR_LIT>' , c_float ) , <EOL> ( '<STR_LIT>' , c_float ) , <EOL> ( '<STR_LIT>' , c_int ) , <EOL> ( '<STR_LIT>' , c_int ) , <EOL> ( '<STR_LIT>' , c_int ) , <EOL> ( '<STR_LIT>' , c_char_p ) , <EOL> ] <EOL> geoip_char_fields = [ name for name , ctype in GeoIPRecord . _fields_ if ctype is c_char_p ] <EOL> geoip_encodings = { <NUM_LIT:0> : '<STR_LIT>' , <EOL> <NUM_LIT:1> : '<STR_LIT:utf8>' , <EOL> } <EOL> class GeoIPTag ( Structure ) : pass <EOL> RECTYPE = POINTER ( GeoIPRecord ) <EOL> DBTYPE = POINTER ( GeoIPTag ) <EOL> if hasattr ( lgeoip , '<STR_LIT>' ) : <EOL> GeoIP_lib_version = lgeoip . GeoIP_lib_version <EOL> GeoIP_lib_version . argtypes = None <EOL> GeoIP_lib_version . restype = c_char_p <EOL> else : <EOL> GeoIP_lib_version = None <EOL> GeoIPRecord_delete = lgeoip . GeoIPRecord_delete <EOL> GeoIPRecord_delete . argtypes = [ RECTYPE ] <EOL> GeoIPRecord_delete . restype = None <EOL> def check_record ( result , func , cargs ) : <EOL> if bool ( result ) : <EOL> rec = result . contents <EOL> record = dict ( ( fld , getattr ( rec , fld ) ) for fld , ctype in rec . _fields_ ) <EOL> encoding = geoip_encodings [ record [ '<STR_LIT>' ] ] <EOL> for char_field in geoip_char_fields : <EOL> if record [ char_field ] : <EOL> record [ char_field ] = record [ char_field ] . decode ( encoding ) <EOL> GeoIPRecord_delete ( result ) <EOL> return record <EOL> else : <EOL> return None <EOL> def record_output ( func ) : <EOL> func . argtypes = [ DBTYPE , c_char_p ] <EOL> func . restype = RECTYPE <EOL> func . errcheck = check_record <EOL> return func <EOL> GeoIP_record_by_addr = record_output ( lgeoip . GeoIP_record_by_addr ) <EOL> GeoIP_record_by_name = record_output ( lgeoip . GeoIP_record_by_name ) <EOL> GeoIP_open = lgeoip . GeoIP_open <EOL> GeoIP_open . restype = DBTYPE <EOL> GeoIP_delete = lgeoip . GeoIP_delete <EOL> GeoIP_delete . argtypes = [ DBTYPE ] <EOL> GeoIP_delete . restype = None <EOL> class geoip_char_p ( c_char_p ) : <EOL> pass <EOL> def check_string ( result , func , cargs ) : <EOL> if result : <EOL> s = string_at ( result ) <EOL> free ( result ) <EOL> else : <EOL> s = '<STR_LIT>' <EOL> return s <EOL> GeoIP_database_info = lgeoip . GeoIP_database_info <EOL> GeoIP_database_info . restype = geoip_char_p <EOL> GeoIP_database_info . errcheck = check_string <EOL> def string_output ( func ) : <EOL> func . restype = c_char_p <EOL> return func <EOL> GeoIP_country_code_by_addr = string_output ( lgeoip . GeoIP_country_code_by_addr ) <EOL> GeoIP_country_code_by_name = string_output ( lgeoip . GeoIP_country_code_by_name ) <EOL> GeoIP_country_name_by_addr = string_output ( lgeoip . GeoIP_country_name_by_addr ) <EOL> GeoIP_country_name_by_name = string_output ( lgeoip . GeoIP_country_name_by_name ) </s>
|
<s> from __future__ import absolute_import <EOL> from django . contrib . gis import feeds <EOL> from . models import City <EOL> class TestGeoRSS1 ( feeds . Feed ) : <EOL> link = '<STR_LIT>' <EOL> title = '<STR_LIT>' <EOL> def items ( self ) : <EOL> return City . objects . all ( ) <EOL> def item_link ( self , item ) : <EOL> return '<STR_LIT>' % item . pk <EOL> def item_geometry ( self , item ) : <EOL> return item . point <EOL> class TestGeoRSS2 ( TestGeoRSS1 ) : <EOL> def geometry ( self , obj ) : <EOL> return ( - <NUM_LIT> , - <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> def item_geometry ( self , item ) : <EOL> return item . point . x , item . point . y <EOL> class TestGeoAtom1 ( TestGeoRSS1 ) : <EOL> feed_type = feeds . GeoAtom1Feed <EOL> class TestGeoAtom2 ( TestGeoRSS2 ) : <EOL> feed_type = feeds . GeoAtom1Feed <EOL> def geometry ( self , obj ) : <EOL> return ( ( - <NUM_LIT> , - <NUM_LIT> ) , ( <NUM_LIT> , <NUM_LIT> ) ) <EOL> class TestW3CGeo1 ( TestGeoRSS1 ) : <EOL> feed_type = feeds . W3CGeoFeed <EOL> class TestW3CGeo2 ( TestGeoRSS2 ) : <EOL> feed_type = feeds . W3CGeoFeed <EOL> class TestW3CGeo3 ( TestGeoRSS1 ) : <EOL> feed_type = feeds . W3CGeoFeed <EOL> def item_geometry ( self , item ) : <EOL> from django . contrib . gis . geos import Polygon <EOL> return Polygon ( ( ( <NUM_LIT:0> , <NUM_LIT:0> ) , ( <NUM_LIT:0> , <NUM_LIT:1> ) , ( <NUM_LIT:1> , <NUM_LIT:1> ) , ( <NUM_LIT:1> , <NUM_LIT:0> ) , ( <NUM_LIT:0> , <NUM_LIT:0> ) ) ) <EOL> feed_dict = { <EOL> '<STR_LIT>' : TestGeoRSS1 , <EOL> '<STR_LIT>' : TestGeoRSS2 , <EOL> '<STR_LIT>' : TestGeoAtom1 , <EOL> '<STR_LIT>' : TestGeoAtom2 , <EOL> '<STR_LIT>' : TestW3CGeo1 , <EOL> '<STR_LIT>' : TestW3CGeo2 , <EOL> '<STR_LIT>' : TestW3CGeo3 , <EOL> } </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import <EOL> import re <EOL> from django . core . validators import EMPTY_VALUES <EOL> from django . forms import ValidationError <EOL> from django . forms . fields import Field , CharField , Select <EOL> from django . utils . encoding import smart_unicode <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> phone_digits_re = re . compile ( r'<STR_LIT>' ) <EOL> sin_re = re . compile ( r"<STR_LIT>" ) <EOL> class CAPostalCodeField ( CharField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> postcode_regex = re . compile ( r'<STR_LIT>' ) <EOL> def clean ( self , value ) : <EOL> value = super ( CAPostalCodeField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> postcode = value . upper ( ) . strip ( ) <EOL> m = self . postcode_regex . match ( postcode ) <EOL> if not m : <EOL> raise ValidationError ( self . default_error_messages [ '<STR_LIT>' ] ) <EOL> return "<STR_LIT>" % ( m . group ( <NUM_LIT:1> ) , m . group ( <NUM_LIT:2> ) ) <EOL> class CAPhoneNumberField ( Field ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> } <EOL> def clean ( self , value ) : <EOL> """<STR_LIT>""" <EOL> super ( CAPhoneNumberField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> value = re . sub ( '<STR_LIT>' , '<STR_LIT>' , smart_unicode ( value ) ) <EOL> m = phone_digits_re . search ( value ) <EOL> if m : <EOL> return u'<STR_LIT>' % ( m . group ( <NUM_LIT:1> ) , m . group ( <NUM_LIT:2> ) , m . group ( <NUM_LIT:3> ) ) <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> class CAProvinceField ( Field ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : u'<STR_LIT>' , <EOL> } <EOL> def clean ( self , value ) : <EOL> super ( CAProvinceField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> try : <EOL> value = value . strip ( ) . lower ( ) <EOL> except AttributeError : <EOL> pass <EOL> else : <EOL> from django . contrib . localflavor . ca . ca_provinces import PROVINCES_NORMALIZED <EOL> try : <EOL> return PROVINCES_NORMALIZED [ value . strip ( ) . lower ( ) ] . decode ( '<STR_LIT:ascii>' ) <EOL> except KeyError : <EOL> pass <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> class CAProvinceSelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> from django . contrib . localflavor . ca . ca_provinces import PROVINCE_CHOICES <EOL> super ( CAProvinceSelect , self ) . __init__ ( attrs , choices = PROVINCE_CHOICES ) <EOL> class CASocialInsuranceNumberField ( Field ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( '<STR_LIT>' ) , <EOL> } <EOL> def clean ( self , value ) : <EOL> super ( CASocialInsuranceNumberField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> match = re . match ( sin_re , value ) <EOL> if not match : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> number = u'<STR_LIT>' % ( match . group ( <NUM_LIT:1> ) , match . group ( <NUM_LIT:2> ) , match . group ( <NUM_LIT:3> ) ) <EOL> check_number = u'<STR_LIT>' % ( match . group ( <NUM_LIT:1> ) , match . group ( <NUM_LIT:2> ) , match . group ( <NUM_LIT:3> ) ) <EOL> if not self . luhn_checksum_is_valid ( check_number ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return number <EOL> def luhn_checksum_is_valid ( self , number ) : <EOL> """<STR_LIT>""" <EOL> sum = <NUM_LIT:0> <EOL> num_digits = len ( number ) <EOL> oddeven = num_digits & <NUM_LIT:1> <EOL> for count in range ( <NUM_LIT:0> , num_digits ) : <EOL> digit = int ( number [ count ] ) <EOL> if not ( ( count & <NUM_LIT:1> ) ^ oddeven ) : <EOL> digit = digit * <NUM_LIT:2> <EOL> if digit > <NUM_LIT:9> : <EOL> digit = digit - <NUM_LIT:9> <EOL> sum = sum + digit <EOL> return ( ( sum % <NUM_LIT:10> ) == <NUM_LIT:0> ) </s>
|
<s> from __future__ import absolute_import <EOL> import datetime <EOL> from django . core . validators import EMPTY_VALUES <EOL> from django . forms import ValidationError <EOL> from django . forms . fields import RegexField , Select <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from django . contrib . localflavor . mk . mk_choices import MK_MUNICIPALITIES <EOL> class MKIdentityCardNumberField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = None <EOL> kwargs [ '<STR_LIT:max_length>' ] = <NUM_LIT:8> <EOL> regex = ur '<STR_LIT>' <EOL> super ( MKIdentityCardNumberField , self ) . __init__ ( regex , * args , ** kwargs ) <EOL> class MKMunicipalitySelect ( Select ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , attrs = None ) : <EOL> super ( MKMunicipalitySelect , self ) . __init__ ( attrs , choices = MK_MUNICIPALITIES ) <EOL> class UMCNField ( RegexField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT:date>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = None <EOL> kwargs [ '<STR_LIT:max_length>' ] = <NUM_LIT> <EOL> super ( UMCNField , self ) . __init__ ( r'<STR_LIT>' , * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> value = super ( UMCNField , self ) . clean ( value ) <EOL> if value in EMPTY_VALUES : <EOL> return u'<STR_LIT>' <EOL> if not self . _validate_date_part ( value ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT:date>' ] ) <EOL> if self . _validate_checksum ( value ) : <EOL> return value <EOL> else : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> def _validate_checksum ( self , value ) : <EOL> a , b , c , d , e , f , g , h , i , j , k , l , K = [ int ( digit ) for digit in value ] <EOL> m = <NUM_LIT:11> - ( ( <NUM_LIT:7> * ( a + g ) + <NUM_LIT:6> * ( b + h ) + <NUM_LIT:5> * ( c + i ) + <NUM_LIT:4> * ( d + j ) + <NUM_LIT:3> * ( e + k ) + <NUM_LIT:2> * ( f + l ) ) % <NUM_LIT:11> ) <EOL> if ( m >= <NUM_LIT:1> and m <= <NUM_LIT:9> ) and K == m : <EOL> return True <EOL> elif m == <NUM_LIT:11> and K == <NUM_LIT:0> : <EOL> return True <EOL> else : <EOL> return False <EOL> def _validate_date_part ( self , value ) : <EOL> daypart , monthpart , yearpart = int ( value [ : <NUM_LIT:2> ] ) , int ( value [ <NUM_LIT:2> : <NUM_LIT:4> ] ) , int ( value [ <NUM_LIT:4> : <NUM_LIT:7> ] ) <EOL> if yearpart >= <NUM_LIT> : <EOL> yearpart += <NUM_LIT:1000> <EOL> else : <EOL> yearpart += <NUM_LIT> <EOL> try : <EOL> date = datetime . datetime ( year = yearpart , month = monthpart , day = daypart ) . date ( ) <EOL> except ValueError : <EOL> return False <EOL> if date >= datetime . datetime . now ( ) . date ( ) : <EOL> return False <EOL> return True </s>
|
<s> """<STR_LIT>""" <EOL> import warnings <EOL> from django import template <EOL> from django . conf import settings <EOL> from django . utils . encoding import smart_str , force_unicode <EOL> from django . utils . safestring import mark_safe <EOL> register = template . Library ( ) <EOL> @ register . filter ( is_safe = True ) <EOL> def textile ( value ) : <EOL> try : <EOL> import textile <EOL> except ImportError : <EOL> if settings . DEBUG : <EOL> raise template . TemplateSyntaxError ( "<STR_LIT>" ) <EOL> return force_unicode ( value ) <EOL> else : <EOL> return mark_safe ( force_unicode ( textile . textile ( smart_str ( value ) , encoding = '<STR_LIT:utf-8>' , output = '<STR_LIT:utf-8>' ) ) ) <EOL> @ register . filter ( is_safe = True ) <EOL> def markdown ( value , arg = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> import markdown <EOL> except ImportError : <EOL> if settings . DEBUG : <EOL> raise template . TemplateSyntaxError ( "<STR_LIT>" ) <EOL> return force_unicode ( value ) <EOL> else : <EOL> if hasattr ( markdown , '<STR_LIT:version>' ) : <EOL> extensions = [ e for e in arg . split ( "<STR_LIT:U+002C>" ) if e ] <EOL> if len ( extensions ) > <NUM_LIT:0> and extensions [ <NUM_LIT:0> ] == "<STR_LIT>" : <EOL> extensions = extensions [ <NUM_LIT:1> : ] <EOL> safe_mode = True <EOL> else : <EOL> safe_mode = False <EOL> python_markdown_deprecation = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> markdown_vers = getattr ( markdown , "<STR_LIT>" , None ) <EOL> if markdown_vers < ( <NUM_LIT:1> , <NUM_LIT:7> ) : <EOL> warnings . warn ( python_markdown_deprecation , DeprecationWarning ) <EOL> return mark_safe ( force_unicode ( markdown . markdown ( smart_str ( value ) , extensions , safe_mode = safe_mode ) ) ) <EOL> else : <EOL> if markdown_vers >= ( <NUM_LIT:2> , <NUM_LIT:1> ) : <EOL> if safe_mode : <EOL> return mark_safe ( markdown . markdown ( force_unicode ( value ) , extensions , safe_mode = safe_mode , enable_attributes = False ) ) <EOL> else : <EOL> return mark_safe ( markdown . markdown ( force_unicode ( value ) , extensions , safe_mode = safe_mode ) ) <EOL> else : <EOL> warnings . warn ( python_markdown_deprecation , DeprecationWarning ) <EOL> return mark_safe ( markdown . markdown ( force_unicode ( value ) , extensions , safe_mode = safe_mode ) ) <EOL> else : <EOL> warnings . warn ( python_markdown_deprecation , DeprecationWarning ) <EOL> return mark_safe ( force_unicode ( markdown . markdown ( smart_str ( value ) ) ) ) <EOL> @ register . filter ( is_safe = True ) <EOL> def restructuredtext ( value ) : <EOL> try : <EOL> from docutils . core import publish_parts <EOL> except ImportError : <EOL> if settings . DEBUG : <EOL> raise template . TemplateSyntaxError ( "<STR_LIT>" ) <EOL> return force_unicode ( value ) <EOL> else : <EOL> docutils_settings = getattr ( settings , "<STR_LIT>" , { } ) <EOL> parts = publish_parts ( source = smart_str ( value ) , writer_name = "<STR_LIT>" , settings_overrides = docutils_settings ) <EOL> return mark_safe ( force_unicode ( parts [ "<STR_LIT>" ] ) ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . db . models import signals <EOL> from django . db import connections <EOL> from django . db import router <EOL> from django . contrib . sites . models import Site <EOL> from django . contrib . sites import models as site_app <EOL> from django . core . management . color import no_style <EOL> def create_default_site ( app , created_models , verbosity , db , ** kwargs ) : <EOL> if Site in created_models and router . allow_syncdb ( db , Site ) : <EOL> if verbosity >= <NUM_LIT:2> : <EOL> print "<STR_LIT>" <EOL> Site ( pk = <NUM_LIT:1> , domain = "<STR_LIT>" , name = "<STR_LIT>" ) . save ( using = db ) <EOL> sequence_sql = connections [ db ] . ops . sequence_reset_sql ( no_style ( ) , [ Site ] ) <EOL> if sequence_sql : <EOL> if verbosity >= <NUM_LIT:2> : <EOL> print "<STR_LIT>" <EOL> cursor = connections [ db ] . cursor ( ) <EOL> for command in sequence_sql : <EOL> cursor . execute ( command ) <EOL> Site . objects . clear_cache ( ) <EOL> signals . post_syncdb . connect ( create_default_site , sender = site_app ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . conf import settings <EOL> from django . core . exceptions import ImproperlyConfigured <EOL> from django . utils . importlib import import_module <EOL> from django . core . mail . utils import CachedDnsName , DNS_NAME <EOL> from django . core . mail . message import ( <EOL> EmailMessage , EmailMultiAlternatives , <EOL> SafeMIMEText , SafeMIMEMultipart , <EOL> DEFAULT_ATTACHMENT_MIME_TYPE , make_msgid , <EOL> BadHeaderError , forbid_multi_line_headers ) <EOL> def get_connection ( backend = None , fail_silently = False , ** kwds ) : <EOL> """<STR_LIT>""" <EOL> path = backend or settings . EMAIL_BACKEND <EOL> try : <EOL> mod_name , klass_name = path . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> mod = import_module ( mod_name ) <EOL> except ImportError , e : <EOL> raise ImproperlyConfigured ( ( '<STR_LIT>' <EOL> % ( mod_name , e ) ) ) <EOL> try : <EOL> klass = getattr ( mod , klass_name ) <EOL> except AttributeError : <EOL> raise ImproperlyConfigured ( ( '<STR_LIT>' <EOL> '<STR_LIT>' % ( mod_name , klass_name ) ) ) <EOL> return klass ( fail_silently = fail_silently , ** kwds ) <EOL> def send_mail ( subject , message , from_email , recipient_list , <EOL> fail_silently = False , auth_user = None , auth_password = None , <EOL> connection = None ) : <EOL> """<STR_LIT>""" <EOL> connection = connection or get_connection ( username = auth_user , <EOL> password = auth_password , <EOL> fail_silently = fail_silently ) <EOL> return EmailMessage ( subject , message , from_email , recipient_list , <EOL> connection = connection ) . send ( ) <EOL> def send_mass_mail ( datatuple , fail_silently = False , auth_user = None , <EOL> auth_password = None , connection = None ) : <EOL> """<STR_LIT>""" <EOL> connection = connection or get_connection ( username = auth_user , <EOL> password = auth_password , <EOL> fail_silently = fail_silently ) <EOL> messages = [ EmailMessage ( subject , message , sender , recipient ) <EOL> for subject , message , sender , recipient in datatuple ] <EOL> return connection . send_messages ( messages ) <EOL> def mail_admins ( subject , message , fail_silently = False , connection = None , <EOL> html_message = None ) : <EOL> """<STR_LIT>""" <EOL> if not settings . ADMINS : <EOL> return <EOL> mail = EmailMultiAlternatives ( u'<STR_LIT>' % ( settings . EMAIL_SUBJECT_PREFIX , subject ) , <EOL> message , settings . SERVER_EMAIL , [ a [ <NUM_LIT:1> ] for a in settings . ADMINS ] , <EOL> connection = connection ) <EOL> if html_message : <EOL> mail . attach_alternative ( html_message , '<STR_LIT>' ) <EOL> mail . send ( fail_silently = fail_silently ) <EOL> def mail_managers ( subject , message , fail_silently = False , connection = None , <EOL> html_message = None ) : <EOL> """<STR_LIT>""" <EOL> if not settings . MANAGERS : <EOL> return <EOL> mail = EmailMultiAlternatives ( u'<STR_LIT>' % ( settings . EMAIL_SUBJECT_PREFIX , subject ) , <EOL> message , settings . SERVER_EMAIL , [ a [ <NUM_LIT:1> ] for a in settings . MANAGERS ] , <EOL> connection = connection ) <EOL> if html_message : <EOL> mail . attach_alternative ( html_message , '<STR_LIT>' ) <EOL> mail . send ( fail_silently = fail_silently ) </s>
|
<s> import sys <EOL> import os <EOL> from optparse import make_option , OptionParser <EOL> from django . conf import settings <EOL> from django . core . management . base import BaseCommand <EOL> from django . test . utils import get_runner <EOL> class Command ( BaseCommand ) : <EOL> option_list = BaseCommand . option_list + ( <EOL> make_option ( '<STR_LIT>' , <EOL> action = '<STR_LIT>' , dest = '<STR_LIT>' , default = True , <EOL> help = '<STR_LIT>' ) , <EOL> make_option ( '<STR_LIT>' , <EOL> action = '<STR_LIT:store_true>' , dest = '<STR_LIT>' , default = False , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> make_option ( '<STR_LIT>' , <EOL> action = '<STR_LIT:store>' , dest = '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> make_option ( '<STR_LIT>' , <EOL> action = '<STR_LIT:store>' , dest = '<STR_LIT>' , default = None , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> ) <EOL> help = ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> args = '<STR_LIT>' <EOL> requires_model_validation = False <EOL> def __init__ ( self ) : <EOL> self . test_runner = None <EOL> super ( Command , self ) . __init__ ( ) <EOL> def run_from_argv ( self , argv ) : <EOL> """<STR_LIT>""" <EOL> option = '<STR_LIT>' <EOL> for arg in argv [ <NUM_LIT:2> : ] : <EOL> if arg . startswith ( option ) : <EOL> self . test_runner = arg [ len ( option ) : ] <EOL> break <EOL> super ( Command , self ) . run_from_argv ( argv ) <EOL> def create_parser ( self , prog_name , subcommand ) : <EOL> test_runner_class = get_runner ( settings , self . test_runner ) <EOL> options = self . option_list + getattr ( <EOL> test_runner_class , '<STR_LIT>' , ( ) ) <EOL> return OptionParser ( prog = prog_name , <EOL> usage = self . usage ( subcommand ) , <EOL> version = self . get_version ( ) , <EOL> option_list = options ) <EOL> def handle ( self , * test_labels , ** options ) : <EOL> from django . conf import settings <EOL> from django . test . utils import get_runner <EOL> TestRunner = get_runner ( settings , options . get ( '<STR_LIT>' ) ) <EOL> options [ '<STR_LIT>' ] = int ( options . get ( '<STR_LIT>' ) ) <EOL> if options . get ( '<STR_LIT>' ) is not None : <EOL> os . environ [ '<STR_LIT>' ] = options [ '<STR_LIT>' ] <EOL> del options [ '<STR_LIT>' ] <EOL> test_runner = TestRunner ( ** options ) <EOL> failures = test_runner . run_tests ( test_labels ) <EOL> if failures : <EOL> sys . exit ( bool ( failures ) ) </s>
|
<s> import psycopg2 . extensions <EOL> from django . db . backends . creation import BaseDatabaseCreation <EOL> from django . db . backends . util import truncate_name <EOL> class DatabaseCreation ( BaseDatabaseCreation ) : <EOL> data_types = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT:date>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT:text>' , <EOL> '<STR_LIT>' : '<STR_LIT:time>' , <EOL> } <EOL> def sql_table_creation_suffix ( self ) : <EOL> assert self . connection . settings_dict [ '<STR_LIT>' ] is None , "<STR_LIT>" <EOL> if self . connection . settings_dict [ '<STR_LIT>' ] : <EOL> return "<STR_LIT>" % self . connection . settings_dict [ '<STR_LIT>' ] <EOL> return '<STR_LIT>' <EOL> def sql_indexes_for_field ( self , model , f , style ) : <EOL> if f . db_index and not f . unique : <EOL> qn = self . connection . ops . quote_name <EOL> db_table = model . _meta . db_table <EOL> tablespace = f . db_tablespace or model . _meta . db_tablespace <EOL> if tablespace : <EOL> tablespace_sql = self . connection . ops . tablespace_sql ( tablespace ) <EOL> if tablespace_sql : <EOL> tablespace_sql = '<STR_LIT:U+0020>' + tablespace_sql <EOL> else : <EOL> tablespace_sql = '<STR_LIT>' <EOL> def get_index_sql ( index_name , opclass = '<STR_LIT>' ) : <EOL> return ( style . SQL_KEYWORD ( '<STR_LIT>' ) + '<STR_LIT:U+0020>' + <EOL> style . SQL_TABLE ( qn ( truncate_name ( index_name , self . connection . ops . max_name_length ( ) ) ) ) + '<STR_LIT:U+0020>' + <EOL> style . SQL_KEYWORD ( '<STR_LIT>' ) + '<STR_LIT:U+0020>' + <EOL> style . SQL_TABLE ( qn ( db_table ) ) + '<STR_LIT:U+0020>' + <EOL> "<STR_LIT>" % ( style . SQL_FIELD ( qn ( f . column ) ) , opclass ) + <EOL> "<STR_LIT>" % tablespace_sql ) <EOL> output = [ get_index_sql ( '<STR_LIT>' % ( db_table , f . column ) ) ] <EOL> db_type = f . db_type ( connection = self . connection ) <EOL> if db_type . startswith ( '<STR_LIT>' ) : <EOL> output . append ( get_index_sql ( '<STR_LIT>' % ( db_table , f . column ) , <EOL> '<STR_LIT>' ) ) <EOL> elif db_type . startswith ( '<STR_LIT:text>' ) : <EOL> output . append ( get_index_sql ( '<STR_LIT>' % ( db_table , f . column ) , <EOL> '<STR_LIT>' ) ) <EOL> else : <EOL> output = [ ] <EOL> return output <EOL> def set_autocommit ( self ) : <EOL> self . _prepare_for_test_db_ddl ( ) <EOL> def _prepare_for_test_db_ddl ( self ) : <EOL> """<STR_LIT>""" <EOL> self . connection . connection . rollback ( ) <EOL> self . connection . connection . set_isolation_level ( <EOL> psycopg2 . extensions . ISOLATION_LEVEL_AUTOCOMMIT ) </s>
|
<s> """<STR_LIT>""" <EOL> import traceback <EOL> import weakref <EOL> def safeRef ( target , onDelete = None ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( target , '<STR_LIT>' ) : <EOL> if target . im_self is not None : <EOL> assert hasattr ( target , '<STR_LIT>' ) , """<STR_LIT>""" % ( target , ) <EOL> reference = get_bound_method_weakref ( <EOL> target = target , <EOL> onDelete = onDelete <EOL> ) <EOL> return reference <EOL> if callable ( onDelete ) : <EOL> return weakref . ref ( target , onDelete ) <EOL> else : <EOL> return weakref . ref ( target ) <EOL> class BoundMethodWeakref ( object ) : <EOL> """<STR_LIT>""" <EOL> _allInstances = weakref . WeakValueDictionary ( ) <EOL> def __new__ ( cls , target , onDelete = None , * arguments , ** named ) : <EOL> """<STR_LIT>""" <EOL> key = cls . calculateKey ( target ) <EOL> current = cls . _allInstances . get ( key ) <EOL> if current is not None : <EOL> current . deletionMethods . append ( onDelete ) <EOL> return current <EOL> else : <EOL> base = super ( BoundMethodWeakref , cls ) . __new__ ( cls ) <EOL> cls . _allInstances [ key ] = base <EOL> base . __init__ ( target , onDelete , * arguments , ** named ) <EOL> return base <EOL> def __init__ ( self , target , onDelete = None ) : <EOL> """<STR_LIT>""" <EOL> def remove ( weak , self = self ) : <EOL> """<STR_LIT>""" <EOL> methods = self . deletionMethods [ : ] <EOL> del self . deletionMethods [ : ] <EOL> try : <EOL> del self . __class__ . _allInstances [ self . key ] <EOL> except KeyError : <EOL> pass <EOL> for function in methods : <EOL> try : <EOL> if callable ( function ) : <EOL> function ( self ) <EOL> except Exception , e : <EOL> try : <EOL> traceback . print_exc ( ) <EOL> except AttributeError , err : <EOL> print '''<STR_LIT>''' % ( <EOL> self , function , e <EOL> ) <EOL> self . deletionMethods = [ onDelete ] <EOL> self . key = self . calculateKey ( target ) <EOL> self . weakSelf = weakref . ref ( target . im_self , remove ) <EOL> self . weakFunc = weakref . ref ( target . im_func , remove ) <EOL> self . selfName = str ( target . im_self ) <EOL> self . funcName = str ( target . im_func . __name__ ) <EOL> def calculateKey ( cls , target ) : <EOL> """<STR_LIT>""" <EOL> return ( id ( target . im_self ) , id ( target . im_func ) ) <EOL> calculateKey = classmethod ( calculateKey ) <EOL> def __str__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return """<STR_LIT>""" % ( <EOL> self . __class__ . __name__ , <EOL> self . selfName , <EOL> self . funcName , <EOL> ) <EOL> __repr__ = __str__ <EOL> def __nonzero__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return self ( ) is not None <EOL> def __cmp__ ( self , other ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( other , self . __class__ ) : <EOL> return cmp ( self . __class__ , type ( other ) ) <EOL> return cmp ( self . key , other . key ) <EOL> def __call__ ( self ) : <EOL> """<STR_LIT>""" <EOL> target = self . weakSelf ( ) <EOL> if target is not None : <EOL> function = self . weakFunc ( ) <EOL> if function is not None : <EOL> return function . __get__ ( target ) <EOL> return None <EOL> class BoundNonDescriptorMethodWeakref ( BoundMethodWeakref ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , target , onDelete = None ) : <EOL> """<STR_LIT>""" <EOL> assert getattr ( target . im_self , target . __name__ ) == target , ( "<STR_LIT>" % <EOL> ( target , target . __name__ , target . im_self ) ) <EOL> super ( BoundNonDescriptorMethodWeakref , self ) . __init__ ( target , onDelete ) <EOL> def __call__ ( self ) : <EOL> """<STR_LIT>""" <EOL> target = self . weakSelf ( ) <EOL> if target is not None : <EOL> function = self . weakFunc ( ) <EOL> if function is not None : <EOL> return getattr ( target , function . __name__ ) <EOL> return None <EOL> def get_bound_method_weakref ( target , onDelete ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( target , '<STR_LIT>' ) : <EOL> return BoundMethodWeakref ( target = target , onDelete = onDelete ) <EOL> else : <EOL> return BoundNonDescriptorMethodWeakref ( target = target , onDelete = onDelete ) </s>
|
<s> try : <EOL> from pkg_resources import resource_string <EOL> except ImportError : <EOL> resource_string = None <EOL> from django . template . base import TemplateDoesNotExist <EOL> from django . template . loader import BaseLoader <EOL> from django . conf import settings <EOL> class Loader ( BaseLoader ) : <EOL> is_usable = resource_string is not None <EOL> def load_template_source ( self , template_name , template_dirs = None ) : <EOL> """<STR_LIT>""" <EOL> if resource_string is not None : <EOL> pkg_name = '<STR_LIT>' + template_name <EOL> for app in settings . INSTALLED_APPS : <EOL> try : <EOL> return ( resource_string ( app , pkg_name ) . decode ( settings . FILE_CHARSET ) , '<STR_LIT>' % ( app , pkg_name ) ) <EOL> except : <EOL> pass <EOL> raise TemplateDoesNotExist ( template_name ) <EOL> _loader = Loader ( ) </s>
|
<s> "<STR_LIT>" <EOL> from functools import wraps , update_wrapper , WRAPPER_ASSIGNMENTS <EOL> class classonlymethod ( classmethod ) : <EOL> def __get__ ( self , instance , owner ) : <EOL> if instance is not None : <EOL> raise AttributeError ( "<STR_LIT>" ) <EOL> return super ( classonlymethod , self ) . __get__ ( instance , owner ) <EOL> def method_decorator ( decorator ) : <EOL> """<STR_LIT>""" <EOL> def _dec ( func ) : <EOL> def _wrapper ( self , * args , ** kwargs ) : <EOL> @ decorator <EOL> def bound_func ( * args2 , ** kwargs2 ) : <EOL> return func ( self , * args2 , ** kwargs2 ) <EOL> return bound_func ( * args , ** kwargs ) <EOL> @ decorator <EOL> def dummy ( * args , ** kwargs ) : <EOL> pass <EOL> update_wrapper ( _wrapper , dummy ) <EOL> update_wrapper ( _wrapper , func ) <EOL> return _wrapper <EOL> update_wrapper ( _dec , decorator ) <EOL> _dec . __name__ = '<STR_LIT>' % decorator . __name__ <EOL> return _dec <EOL> def decorator_from_middleware_with_args ( middleware_class ) : <EOL> """<STR_LIT>""" <EOL> return make_middleware_decorator ( middleware_class ) <EOL> def decorator_from_middleware ( middleware_class ) : <EOL> """<STR_LIT>""" <EOL> return make_middleware_decorator ( middleware_class ) ( ) <EOL> def available_attrs ( fn ) : <EOL> """<STR_LIT>""" <EOL> return tuple ( a for a in WRAPPER_ASSIGNMENTS if hasattr ( fn , a ) ) <EOL> def make_middleware_decorator ( middleware_class ) : <EOL> def _make_decorator ( * m_args , ** m_kwargs ) : <EOL> middleware = middleware_class ( * m_args , ** m_kwargs ) <EOL> def _decorator ( view_func ) : <EOL> @ wraps ( view_func , assigned = available_attrs ( view_func ) ) <EOL> def _wrapped_view ( request , * args , ** kwargs ) : <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> result = middleware . process_request ( request ) <EOL> if result is not None : <EOL> return result <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> result = middleware . process_view ( request , view_func , args , kwargs ) <EOL> if result is not None : <EOL> return result <EOL> try : <EOL> response = view_func ( request , * args , ** kwargs ) <EOL> except Exception , e : <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> result = middleware . process_exception ( request , e ) <EOL> if result is not None : <EOL> return result <EOL> raise <EOL> if hasattr ( response , '<STR_LIT>' ) and callable ( response . render ) : <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> response = middleware . process_template_response ( request , response ) <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> callback = lambda response : middleware . process_response ( request , response ) <EOL> response . add_post_render_callback ( callback ) <EOL> else : <EOL> if hasattr ( middleware , '<STR_LIT>' ) : <EOL> return middleware . process_response ( request , response ) <EOL> return response <EOL> return _wrapped_view <EOL> return _decorator <EOL> return _make_decorator </s>
|
<s> import django <EOL> import re <EOL> def get_svn_revision ( path = None ) : <EOL> """<STR_LIT>""" <EOL> rev = None <EOL> if path is None : <EOL> path = django . __path__ [ <NUM_LIT:0> ] <EOL> entries_path = '<STR_LIT>' % path <EOL> try : <EOL> entries = open ( entries_path , '<STR_LIT:r>' ) . read ( ) <EOL> except IOError : <EOL> pass <EOL> else : <EOL> if re . match ( '<STR_LIT>' , entries ) : <EOL> rev_match = re . search ( '<STR_LIT>' , entries ) <EOL> if rev_match : <EOL> rev = rev_match . groups ( ) [ <NUM_LIT:0> ] <EOL> else : <EOL> from xml . dom import minidom <EOL> dom = minidom . parse ( entries_path ) <EOL> rev = dom . getElementsByTagName ( '<STR_LIT>' ) [ <NUM_LIT:0> ] . getAttribute ( '<STR_LIT>' ) <EOL> if rev : <EOL> return u'<STR_LIT>' % rev <EOL> return u'<STR_LIT>' </s>
|
<s> """<STR_LIT>""" <EOL> from django . db import models <EOL> GENDER_CHOICES = ( <EOL> ( '<STR_LIT:M>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:F>' , '<STR_LIT>' ) , <EOL> ) <EOL> class Person ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:20> ) <EOL> gender = models . CharField ( max_length = <NUM_LIT:1> , choices = GENDER_CHOICES ) <EOL> def __unicode__ ( self ) : <EOL> return self . name </s>
|
<s> from django . db import models <EOL> class Article ( models . Model ) : <EOL> headline = models . CharField ( max_length = <NUM_LIT:100> , default = '<STR_LIT>' ) <EOL> pub_date = models . DateTimeField ( ) <EOL> def __unicode__ ( self ) : <EOL> return self . headline <EOL> class Meta : <EOL> app_label = '<STR_LIT>' <EOL> ordering = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class Book ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> class Meta : <EOL> ordering = ( '<STR_LIT:name>' , ) </s>
|
<s> """<STR_LIT>""" <EOL> from django . db import models <EOL> class Publication ( models . Model ) : <EOL> title = models . CharField ( max_length = <NUM_LIT:30> ) <EOL> def __unicode__ ( self ) : <EOL> return self . title <EOL> class Meta : <EOL> ordering = ( '<STR_LIT:title>' , ) <EOL> class Article ( models . Model ) : <EOL> headline = models . CharField ( max_length = <NUM_LIT:100> ) <EOL> publications = models . ManyToManyField ( Publication ) <EOL> def __unicode__ ( self ) : <EOL> return self . headline <EOL> class Meta : <EOL> ordering = ( '<STR_LIT>' , ) </s>
|
<s> from __future__ import with_statement , absolute_import <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . db import connection <EOL> from django . test import TestCase <EOL> from django . test . utils import override_settings <EOL> from . models import ( Author , Book , Reader , Qualification , Teacher , Department , <EOL> TaggedItem , Bookmark , AuthorAddress , FavoriteAuthors , AuthorWithAge , <EOL> BookWithYear , Person , House , Room , Employee , Comment ) <EOL> class PrefetchRelatedTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . book1 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> self . book2 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> self . book3 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> self . book4 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> self . author1 = Author . objects . create ( name = "<STR_LIT>" , <EOL> first_book = self . book1 ) <EOL> self . author2 = Author . objects . create ( name = "<STR_LIT>" , <EOL> first_book = self . book1 ) <EOL> self . author3 = Author . objects . create ( name = "<STR_LIT>" , <EOL> first_book = self . book1 ) <EOL> self . author4 = Author . objects . create ( name = "<STR_LIT>" , <EOL> first_book = self . book4 ) <EOL> self . book1 . authors . add ( self . author1 , self . author2 , self . author3 ) <EOL> self . book2 . authors . add ( self . author1 ) <EOL> self . book3 . authors . add ( self . author3 ) <EOL> self . book4 . authors . add ( self . author4 ) <EOL> self . reader1 = Reader . objects . create ( name = "<STR_LIT>" ) <EOL> self . reader2 = Reader . objects . create ( name = "<STR_LIT>" ) <EOL> self . reader1 . books_read . add ( self . book1 , self . book4 ) <EOL> self . reader2 . books_read . add ( self . book2 , self . book4 ) <EOL> def test_m2m_forward ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lists = [ list ( b . authors . all ( ) ) for b in Book . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> normal_lists = [ list ( b . authors . all ( ) ) for b in Book . objects . all ( ) ] <EOL> self . assertEqual ( lists , normal_lists ) <EOL> def test_m2m_reverse ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lists = [ list ( a . books . all ( ) ) for a in Author . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> normal_lists = [ list ( a . books . all ( ) ) for a in Author . objects . all ( ) ] <EOL> self . assertEqual ( lists , normal_lists ) <EOL> def test_foreignkey_forward ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> books = [ a . first_book for a in Author . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> normal_books = [ a . first_book for a in Author . objects . all ( ) ] <EOL> self . assertEqual ( books , normal_books ) <EOL> def test_foreignkey_reverse ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in Book . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> self . assertQuerysetEqual ( self . book2 . authors . all ( ) , [ u"<STR_LIT>" ] ) <EOL> def test_survives_clone ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in Book . objects . prefetch_related ( '<STR_LIT>' ) . exclude ( id = <NUM_LIT:1000> ) ] <EOL> def test_len ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Book . objects . prefetch_related ( '<STR_LIT>' ) <EOL> length = len ( qs ) <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in qs ] <EOL> def test_bool ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Book . objects . prefetch_related ( '<STR_LIT>' ) <EOL> x = bool ( qs ) <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in qs ] <EOL> def test_count ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Book . objects . prefetch_related ( '<STR_LIT>' ) <EOL> [ b . first_time_authors . count ( ) for b in qs ] <EOL> def test_exists ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Book . objects . prefetch_related ( '<STR_LIT>' ) <EOL> [ b . first_time_authors . exists ( ) for b in qs ] <EOL> def test_clear ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . assertNumQueries ( <NUM_LIT:5> ) : <EOL> with_prefetch = Author . objects . prefetch_related ( '<STR_LIT>' ) <EOL> without_prefetch = with_prefetch . prefetch_related ( None ) <EOL> lists = [ list ( a . books . all ( ) ) for a in without_prefetch ] <EOL> def test_m2m_then_m2m ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Author . objects . prefetch_related ( '<STR_LIT>' ) <EOL> lists = [ [ [ unicode ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ u"<STR_LIT>" ] , [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] , [ ] ] , <EOL> [ [ u"<STR_LIT>" , u"<STR_LIT>" ] ] , <EOL> ] ) <EOL> def test_overriding_prefetch ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Author . objects . prefetch_related ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> lists = [ [ [ unicode ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ u"<STR_LIT>" ] , [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] , [ ] ] , <EOL> [ [ u"<STR_LIT>" , u"<STR_LIT>" ] ] , <EOL> ] ) <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Author . objects . prefetch_related ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> lists = [ [ [ unicode ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ u"<STR_LIT>" ] , [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] ] , <EOL> [ [ u"<STR_LIT>" ] , [ ] ] , <EOL> [ [ u"<STR_LIT>" , u"<STR_LIT>" ] ] , <EOL> ] ) <EOL> def test_get ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> author = Author . objects . prefetch_related ( '<STR_LIT>' ) . get ( name = "<STR_LIT>" ) <EOL> lists = [ [ unicode ( r ) for r in b . read_by . all ( ) ] <EOL> for b in author . books . all ( ) ] <EOL> self . assertEqual ( lists , [ [ u"<STR_LIT>" ] , [ u"<STR_LIT>" ] ] ) <EOL> def test_foreign_key_then_m2m ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Author . objects . select_related ( '<STR_LIT>' ) . prefetch_related ( '<STR_LIT>' ) <EOL> lists = [ [ unicode ( r ) for r in a . first_book . read_by . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , [ [ u"<STR_LIT>" ] , <EOL> [ u"<STR_LIT>" ] , <EOL> [ u"<STR_LIT>" ] , <EOL> [ u"<STR_LIT>" , "<STR_LIT>" ] ] ) <EOL> def test_attribute_error ( self ) : <EOL> qs = Reader . objects . all ( ) . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertRaises ( AttributeError ) as cm : <EOL> list ( qs ) <EOL> self . assertTrue ( '<STR_LIT>' in str ( cm . exception ) ) <EOL> def test_invalid_final_lookup ( self ) : <EOL> qs = Book . objects . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertRaises ( ValueError ) as cm : <EOL> list ( qs ) <EOL> self . assertTrue ( '<STR_LIT>' in str ( cm . exception ) ) <EOL> self . assertTrue ( "<STR_LIT:name>" in str ( cm . exception ) ) <EOL> class DefaultManagerTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . qual1 = Qualification . objects . create ( name = "<STR_LIT>" ) <EOL> self . qual2 = Qualification . objects . create ( name = "<STR_LIT>" ) <EOL> self . qual3 = Qualification . objects . create ( name = "<STR_LIT>" ) <EOL> self . qual4 = Qualification . objects . create ( name = "<STR_LIT>" ) <EOL> self . teacher1 = Teacher . objects . create ( name = "<STR_LIT>" ) <EOL> self . teacher2 = Teacher . objects . create ( name = "<STR_LIT>" ) <EOL> self . teacher3 = Teacher . objects . create ( name = "<STR_LIT>" ) <EOL> self . teacher1 . qualifications . add ( self . qual1 , self . qual2 , self . qual3 , self . qual4 ) <EOL> self . teacher2 . qualifications . add ( self . qual1 ) <EOL> self . teacher3 . qualifications . add ( self . qual2 ) <EOL> self . dept1 = Department . objects . create ( name = "<STR_LIT>" ) <EOL> self . dept2 = Department . objects . create ( name = "<STR_LIT>" ) <EOL> self . dept1 . teachers . add ( self . teacher1 , self . teacher2 ) <EOL> self . dept2 . teachers . add ( self . teacher1 , self . teacher3 ) <EOL> def test_m2m_then_m2m ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Department . objects . prefetch_related ( '<STR_LIT>' ) <EOL> depts = "<STR_LIT>" . join ( [ "<STR_LIT>" % <EOL> ( dept . name , "<STR_LIT:U+002CU+0020>" . join ( unicode ( t ) for t in dept . teachers . all ( ) ) ) <EOL> for dept in qs ] ) <EOL> self . assertEqual ( depts , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> class GenericRelationTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> book1 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> book2 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> book3 = Book . objects . create ( title = "<STR_LIT>" ) <EOL> reader1 = Reader . objects . create ( name = "<STR_LIT>" ) <EOL> reader2 = Reader . objects . create ( name = "<STR_LIT>" ) <EOL> reader3 = Reader . objects . create ( name = "<STR_LIT>" ) <EOL> book1 . read_by . add ( reader1 , reader2 ) <EOL> book2 . read_by . add ( reader2 ) <EOL> book3 . read_by . add ( reader3 ) <EOL> self . book1 , self . book2 , self . book3 = book1 , book2 , book3 <EOL> self . reader1 , self . reader2 , self . reader3 = reader1 , reader2 , reader3 <EOL> def test_prefetch_GFK ( self ) : <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book1 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . reader1 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book2 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . reader3 ) <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = TaggedItem . objects . prefetch_related ( '<STR_LIT>' ) <EOL> list ( qs ) <EOL> def test_prefetch_GFK_nonint_pk ( self ) : <EOL> Comment . objects . create ( comment = "<STR_LIT>" , content_object = self . book1 ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Comment . objects . prefetch_related ( '<STR_LIT>' ) <EOL> [ c . content_object for c in qs ] <EOL> def test_traverse_GFK ( self ) : <EOL> """<STR_LIT>""" <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book1 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book2 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book3 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . reader1 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . reader2 ) <EOL> ct = ContentType . objects . get_for_model ( Book ) <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = TaggedItem . objects . filter ( content_type = ct , tag = '<STR_LIT>' ) . prefetch_related ( '<STR_LIT>' ) <EOL> readers_of_awesome_books = set ( [ r . name for tag in qs <EOL> for r in tag . content_object . read_by . all ( ) ] ) <EOL> self . assertEqual ( readers_of_awesome_books , set ( [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] ) ) <EOL> def test_nullable_GFK ( self ) : <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book1 , <EOL> created_by = self . reader1 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book2 ) <EOL> TaggedItem . objects . create ( tag = "<STR_LIT>" , content_object = self . book3 ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> result = [ t . created_by for t in TaggedItem . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> self . assertEqual ( result , <EOL> [ t . created_by for t in TaggedItem . objects . all ( ) ] ) <EOL> def test_generic_relation ( self ) : <EOL> b = Bookmark . objects . create ( url = '<STR_LIT>' ) <EOL> t1 = TaggedItem . objects . create ( content_object = b , tag = '<STR_LIT>' ) <EOL> t2 = TaggedItem . objects . create ( content_object = b , tag = '<STR_LIT>' ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> tags = [ t . tag for b in Bookmark . objects . prefetch_related ( '<STR_LIT>' ) <EOL> for t in b . tags . all ( ) ] <EOL> self . assertEqual ( sorted ( tags ) , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> class MultiTableInheritanceTest ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . book1 = BookWithYear . objects . create ( <EOL> title = "<STR_LIT>" , published_year = <NUM_LIT> ) <EOL> self . book2 = BookWithYear . objects . create ( <EOL> title = "<STR_LIT>" , published_year = <NUM_LIT> ) <EOL> self . author1 = AuthorWithAge . objects . create ( <EOL> name = '<STR_LIT>' , first_book = self . book1 , age = <NUM_LIT:50> ) <EOL> self . author2 = AuthorWithAge . objects . create ( <EOL> name = '<STR_LIT>' , first_book = self . book1 , age = <NUM_LIT> ) <EOL> self . author3 = AuthorWithAge . objects . create ( <EOL> name = '<STR_LIT>' , first_book = self . book2 , age = <NUM_LIT> ) <EOL> self . authorAddress = AuthorAddress . objects . create ( <EOL> author = self . author1 , address = '<STR_LIT>' ) <EOL> self . book2 . aged_authors . add ( self . author2 , self . author3 ) <EOL> def test_foreignkey ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = AuthorWithAge . objects . prefetch_related ( '<STR_LIT>' ) <EOL> addresses = [ [ unicode ( address ) for address in obj . addresses . all ( ) ] <EOL> for obj in qs ] <EOL> self . assertEquals ( addresses , [ [ unicode ( self . authorAddress ) ] , [ ] , [ ] ] ) <EOL> def test_m2m_to_inheriting_model ( self ) : <EOL> qs = AuthorWithAge . objects . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lst = [ [ unicode ( book ) for book in author . books_with_year . all ( ) ] <EOL> for author in qs ] <EOL> qs = AuthorWithAge . objects . all ( ) <EOL> lst2 = [ [ unicode ( book ) for book in author . books_with_year . all ( ) ] <EOL> for author in qs ] <EOL> self . assertEquals ( lst , lst2 ) <EOL> qs = BookWithYear . objects . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> lst = [ [ unicode ( author ) for author in book . aged_authors . all ( ) ] <EOL> for book in qs ] <EOL> qs = BookWithYear . objects . all ( ) <EOL> lst2 = [ [ unicode ( author ) for author in book . aged_authors . all ( ) ] <EOL> for book in qs ] <EOL> self . assertEquals ( lst , lst2 ) <EOL> def test_parent_link_prefetch ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> [ a . author for a in AuthorWithAge . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> @ override_settings ( DEBUG = True ) <EOL> def test_child_link_prefetch ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> l = [ a . authorwithage for a in Author . objects . prefetch_related ( '<STR_LIT>' ) ] <EOL> self . assertIn ( '<STR_LIT>' , connection . queries [ - <NUM_LIT:1> ] [ '<STR_LIT>' ] ) <EOL> self . assertIn ( '<STR_LIT>' , connection . queries [ - <NUM_LIT:1> ] [ '<STR_LIT>' ] ) <EOL> self . assertEqual ( l , [ a . authorwithage for a in Author . objects . all ( ) ] ) <EOL> class ForeignKeyToFieldTest ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . book = Book . objects . create ( title = "<STR_LIT>" ) <EOL> self . author1 = Author . objects . create ( name = '<STR_LIT>' , first_book = self . book ) <EOL> self . author2 = Author . objects . create ( name = '<STR_LIT>' , first_book = self . book ) <EOL> self . author3 = Author . objects . create ( name = '<STR_LIT>' , first_book = self . book ) <EOL> self . authorAddress = AuthorAddress . objects . create ( <EOL> author = self . author1 , address = '<STR_LIT>' <EOL> ) <EOL> FavoriteAuthors . objects . create ( author = self . author1 , <EOL> likes_author = self . author2 ) <EOL> FavoriteAuthors . objects . create ( author = self . author2 , <EOL> likes_author = self . author3 ) <EOL> FavoriteAuthors . objects . create ( author = self . author3 , <EOL> likes_author = self . author1 ) <EOL> def test_foreignkey ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Author . objects . prefetch_related ( '<STR_LIT>' ) <EOL> addresses = [ [ unicode ( address ) for address in obj . addresses . all ( ) ] <EOL> for obj in qs ] <EOL> self . assertEquals ( addresses , [ [ unicode ( self . authorAddress ) ] , [ ] , [ ] ] ) <EOL> def test_m2m ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Author . objects . all ( ) . prefetch_related ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> favorites = [ ( <EOL> [ unicode ( i_like ) for i_like in author . favorite_authors . all ( ) ] , <EOL> [ unicode ( likes_me ) for likes_me in author . favors_me . all ( ) ] <EOL> ) for author in qs ] <EOL> self . assertEquals ( <EOL> favorites , <EOL> [ <EOL> ( [ unicode ( self . author2 ) ] , [ unicode ( self . author3 ) ] ) , <EOL> ( [ unicode ( self . author3 ) ] , [ unicode ( self . author1 ) ] ) , <EOL> ( [ unicode ( self . author1 ) ] , [ unicode ( self . author2 ) ] ) <EOL> ] <EOL> ) <EOL> class LookupOrderingTest ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . person1 = Person . objects . create ( name = "<STR_LIT>" ) <EOL> self . person2 = Person . objects . create ( name = "<STR_LIT>" ) <EOL> self . house1 = House . objects . create ( address = "<STR_LIT>" ) <EOL> self . house2 = House . objects . create ( address = "<STR_LIT>" ) <EOL> self . house3 = House . objects . create ( address = "<STR_LIT>" ) <EOL> self . house4 = House . objects . create ( address = "<STR_LIT>" ) <EOL> self . room1_1 = Room . objects . create ( name = "<STR_LIT>" , house = self . house1 ) <EOL> self . room1_2 = Room . objects . create ( name = "<STR_LIT>" , house = self . house1 ) <EOL> self . room1_3 = Room . objects . create ( name = "<STR_LIT>" , house = self . house1 ) <EOL> self . room2_1 = Room . objects . create ( name = "<STR_LIT>" , house = self . house2 ) <EOL> self . room2_2 = Room . objects . create ( name = "<STR_LIT>" , house = self . house2 ) <EOL> self . room3_1 = Room . objects . create ( name = "<STR_LIT>" , house = self . house3 ) <EOL> self . room3_2 = Room . objects . create ( name = "<STR_LIT>" , house = self . house3 ) <EOL> self . room3_3 = Room . objects . create ( name = "<STR_LIT>" , house = self . house3 ) <EOL> self . room4_1 = Room . objects . create ( name = "<STR_LIT>" , house = self . house4 ) <EOL> self . room4_2 = Room . objects . create ( name = "<STR_LIT>" , house = self . house4 ) <EOL> self . person1 . houses . add ( self . house1 , self . house2 ) <EOL> self . person2 . houses . add ( self . house3 , self . house4 ) <EOL> def test_order ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:4> ) : <EOL> qs = Person . objects . prefetch_related ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> [ list ( p . primary_house . occupants . all ( ) ) for p in qs ] <EOL> class NullableTest ( TestCase ) : <EOL> def setUp ( self ) : <EOL> boss = Employee . objects . create ( name = "<STR_LIT>" ) <EOL> worker1 = Employee . objects . create ( name = "<STR_LIT>" , boss = boss ) <EOL> worker2 = Employee . objects . create ( name = "<STR_LIT>" , boss = boss ) <EOL> def test_traverse_nullable ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> qs = Employee . objects . select_related ( '<STR_LIT>' ) . prefetch_related ( '<STR_LIT>' ) <EOL> co_serfs = [ list ( e . boss . serfs . all ( ) ) if e . boss is not None else [ ] <EOL> for e in qs ] <EOL> qs2 = Employee . objects . select_related ( '<STR_LIT>' ) <EOL> co_serfs2 = [ list ( e . boss . serfs . all ( ) ) if e . boss is not None else [ ] <EOL> for e in qs2 ] <EOL> self . assertEqual ( co_serfs , co_serfs2 ) <EOL> def test_prefetch_nullable ( self ) : <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> qs = Employee . objects . prefetch_related ( '<STR_LIT>' ) <EOL> co_serfs = [ list ( e . boss . serfs . all ( ) ) if e . boss is not None else [ ] <EOL> for e in qs ] <EOL> qs2 = Employee . objects . all ( ) <EOL> co_serfs2 = [ list ( e . boss . serfs . all ( ) ) if e . boss is not None else [ ] <EOL> for e in qs2 ] <EOL> self . assertEqual ( co_serfs , co_serfs2 ) <EOL> def test_in_bulk ( self ) : <EOL> """<STR_LIT>""" <EOL> boss1 = Employee . objects . create ( name = "<STR_LIT>" ) <EOL> boss2 = Employee . objects . create ( name = "<STR_LIT>" ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> bulk = Employee . objects . prefetch_related ( '<STR_LIT>' ) . in_bulk ( [ boss1 . pk , boss2 . pk ] ) <EOL> for b in bulk . values ( ) : <EOL> list ( b . serfs . all ( ) ) <EOL> class MultiDbTests ( TestCase ) : <EOL> multi_db = True <EOL> def test_using_is_honored_m2m ( self ) : <EOL> B = Book . objects . using ( '<STR_LIT>' ) <EOL> A = Author . objects . using ( '<STR_LIT>' ) <EOL> book1 = B . create ( title = "<STR_LIT>" ) <EOL> book2 = B . create ( title = "<STR_LIT>" ) <EOL> book3 = B . create ( title = "<STR_LIT>" ) <EOL> book4 = B . create ( title = "<STR_LIT>" ) <EOL> author1 = A . create ( name = "<STR_LIT>" , first_book = book1 ) <EOL> author2 = A . create ( name = "<STR_LIT>" , first_book = book1 ) <EOL> author3 = A . create ( name = "<STR_LIT>" , first_book = book1 ) <EOL> author4 = A . create ( name = "<STR_LIT>" , first_book = book4 ) <EOL> book1 . authors . add ( author1 , author2 , author3 ) <EOL> book2 . authors . add ( author1 ) <EOL> book3 . authors . add ( author3 ) <EOL> book4 . authors . add ( author4 ) <EOL> qs1 = B . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> books = "<STR_LIT>" . join ( [ "<STR_LIT>" % <EOL> ( book . title , "<STR_LIT:U+002CU+0020>" . join ( a . name for a in book . authors . all ( ) ) ) <EOL> for book in qs1 ] ) <EOL> self . assertEqual ( books , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> qs2 = A . prefetch_related ( '<STR_LIT>' ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> authors = "<STR_LIT>" . join ( [ "<STR_LIT>" % <EOL> ( author . name , "<STR_LIT:U+002CU+0020>" . join ( b . title for b in author . books . all ( ) ) ) <EOL> for author in qs2 ] ) <EOL> self . assertEquals ( authors , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> def test_using_is_honored_fkey ( self ) : <EOL> B = Book . objects . using ( '<STR_LIT>' ) <EOL> A = Author . objects . using ( '<STR_LIT>' ) <EOL> book1 = B . create ( title = "<STR_LIT>" ) <EOL> book2 = B . create ( title = "<STR_LIT>" ) <EOL> author1 = A . create ( name = "<STR_LIT>" , first_book = book1 ) <EOL> author2 = A . create ( name = "<STR_LIT>" , first_book = book2 ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> books = "<STR_LIT:U+002CU+0020>" . join ( a . first_book . title for a in A . prefetch_related ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( "<STR_LIT>" , books ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> books = "<STR_LIT>" . join ( "<STR_LIT>" % <EOL> ( b . title , "<STR_LIT:U+002CU+0020>" . join ( a . name for a in b . first_time_authors . all ( ) ) ) <EOL> for b in B . prefetch_related ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( books , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> def test_using_is_honored_inheritance ( self ) : <EOL> B = BookWithYear . objects . using ( '<STR_LIT>' ) <EOL> A = AuthorWithAge . objects . using ( '<STR_LIT>' ) <EOL> book1 = B . create ( title = "<STR_LIT>" , published_year = <NUM_LIT> ) <EOL> book2 = B . create ( title = "<STR_LIT>" , published_year = <NUM_LIT> ) <EOL> author1 = A . create ( name = '<STR_LIT>' , first_book = book1 , age = <NUM_LIT:50> ) <EOL> author2 = A . create ( name = '<STR_LIT>' , first_book = book1 , age = <NUM_LIT> ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> authors = "<STR_LIT:U+002CU+0020>" . join ( a . author . name for a in A . prefetch_related ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( authors , "<STR_LIT>" ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> , using = '<STR_LIT>' ) : <EOL> ages = "<STR_LIT:U+002CU+0020>" . join ( str ( a . authorwithage . age ) for a in A . prefetch_related ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( ages , "<STR_LIT>" ) </s>
|
<s> from __future__ import absolute_import <EOL> from django . conf . urls import patterns <EOL> from django . views . generic import RedirectView <EOL> from . import views <EOL> urlpatterns = patterns ( '<STR_LIT>' , <EOL> ( r'<STR_LIT>' , views . get_view ) , <EOL> ( r'<STR_LIT>' , views . post_view ) , <EOL> ( r'<STR_LIT>' , views . view_with_header ) , <EOL> ( r'<STR_LIT>' , views . raw_post_view ) , <EOL> ( r'<STR_LIT>' , views . redirect_view ) , <EOL> ( r'<STR_LIT>' , views . view_with_secure ) , <EOL> ( r'<STR_LIT>' , RedirectView . as_view ( url = '<STR_LIT>' ) ) , <EOL> ( r'<STR_LIT>' , RedirectView . as_view ( url = '<STR_LIT>' , permanent = False ) ) , <EOL> ( r'<STR_LIT>' , RedirectView . as_view ( url = '<STR_LIT>' ) ) , <EOL> ( r'<STR_LIT>' , RedirectView . as_view ( url = '<STR_LIT>' ) ) , <EOL> ( r'<STR_LIT>' , views . double_redirect_view ) , <EOL> ( r'<STR_LIT>' , views . bad_view ) , <EOL> ( r'<STR_LIT>' , views . form_view ) , <EOL> ( r'<STR_LIT>' , views . form_view_with_template ) , <EOL> ( r'<STR_LIT>' , views . login_protected_view ) , <EOL> ( r'<STR_LIT>' , views . login_protected_method_view ) , <EOL> ( r'<STR_LIT>' , views . login_protected_view_changed_redirect ) , <EOL> ( r'<STR_LIT>' , views . permission_protected_view ) , <EOL> ( r'<STR_LIT>' , views . permission_protected_view_exception ) , <EOL> ( r'<STR_LIT>' , views . permission_protected_method_view ) , <EOL> ( r'<STR_LIT>' , views . session_view ) , <EOL> ( r'<STR_LIT>' , views . broken_view ) , <EOL> ( r'<STR_LIT>' , views . mail_sending_view ) , <EOL> ( r'<STR_LIT>' , views . mass_mail_sending_view ) <EOL> ) </s>
|
<s> from __future__ import absolute_import <EOL> from django . core . urlresolvers import reverse <EOL> from django . template . response import TemplateResponse <EOL> from django . test import TestCase <EOL> from . models import Action <EOL> class AdminCustomUrlsTest ( TestCase ) : <EOL> fixtures = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> def setUp ( self ) : <EOL> self . client . login ( username = '<STR_LIT>' , password = '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . client . logout ( ) <EOL> def testBasicAddGet ( self ) : <EOL> """<STR_LIT>""" <EOL> response = self . client . get ( '<STR_LIT>' ) <EOL> self . assertIsInstance ( response , TemplateResponse ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> def testAddWithGETArgs ( self ) : <EOL> response = self . client . get ( '<STR_LIT>' , { '<STR_LIT:name>' : '<STR_LIT>' } ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> self . assertTrue ( <EOL> '<STR_LIT>' in response . content , <EOL> "<STR_LIT>" <EOL> ) <EOL> def testBasicAddPost ( self ) : <EOL> """<STR_LIT>""" <EOL> post_data = { <EOL> '<STR_LIT>' : u'<STR_LIT:1>' , <EOL> "<STR_LIT:name>" : u'<STR_LIT>' , <EOL> "<STR_LIT:description>" : u"<STR_LIT>" , <EOL> } <EOL> response = self . client . post ( '<STR_LIT>' , post_data ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> def testAdminUrlsNoClash ( self ) : <EOL> """<STR_LIT>""" <EOL> response = self . client . get ( '<STR_LIT>' ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> path = reverse ( '<STR_LIT>' % Action . _meta . app_label , <EOL> args = ( '<STR_LIT>' , ) ) <EOL> response = self . client . get ( path ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> path = reverse ( '<STR_LIT>' % Action . _meta . app_label , <EOL> args = ( "<STR_LIT>" , ) ) <EOL> response = self . client . get ( path ) <EOL> self . assertEqual ( response . status_code , <NUM_LIT:200> ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> self . assertContains ( response , '<STR_LIT>' ) </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import with_statement <EOL> import os <EOL> import re <EOL> import shutil <EOL> import socket <EOL> import subprocess <EOL> import sys <EOL> from django import conf , bin , get_version <EOL> from django . conf import settings <EOL> from django . test . simple import DjangoTestSuiteRunner <EOL> from django . utils import unittest <EOL> from django . test import LiveServerTestCase <EOL> test_dir = os . path . dirname ( os . path . dirname ( __file__ ) ) <EOL> expected_query_re = re . compile ( r'<STR_LIT>' , re . IGNORECASE ) <EOL> class AdminScriptTestCase ( unittest . TestCase ) : <EOL> def write_settings ( self , filename , apps = None , is_dir = False , sdict = None ) : <EOL> test_dir = os . path . dirname ( os . path . dirname ( __file__ ) ) <EOL> if is_dir : <EOL> settings_dir = os . path . join ( test_dir , filename ) <EOL> os . mkdir ( settings_dir ) <EOL> settings_file = open ( os . path . join ( settings_dir , '<STR_LIT>' ) , '<STR_LIT:w>' ) <EOL> else : <EOL> settings_file = open ( os . path . join ( test_dir , filename ) , '<STR_LIT:w>' ) <EOL> settings_file . write ( '<STR_LIT>' ) <EOL> exports = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> for s in exports : <EOL> if hasattr ( settings , s ) : <EOL> o = getattr ( settings , s ) <EOL> if not isinstance ( o , dict ) : <EOL> o = "<STR_LIT>" % o <EOL> settings_file . write ( "<STR_LIT>" % ( s , o ) ) <EOL> if apps is None : <EOL> apps = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> settings_file . write ( "<STR_LIT>" % apps ) <EOL> if sdict : <EOL> for k , v in sdict . items ( ) : <EOL> settings_file . write ( "<STR_LIT>" % ( k , v ) ) <EOL> settings_file . close ( ) <EOL> def remove_settings ( self , filename , is_dir = False ) : <EOL> full_name = os . path . join ( test_dir , filename ) <EOL> if is_dir : <EOL> shutil . rmtree ( full_name ) <EOL> else : <EOL> os . remove ( full_name ) <EOL> try : <EOL> if sys . platform . startswith ( '<STR_LIT>' ) : <EOL> os . remove ( re . sub ( r'<STR_LIT>' , '<STR_LIT>' , full_name ) ) <EOL> else : <EOL> os . remove ( full_name + '<STR_LIT:c>' ) <EOL> except OSError : <EOL> pass <EOL> def _ext_backend_paths ( self ) : <EOL> """<STR_LIT>""" <EOL> paths = [ ] <EOL> first_package_re = re . compile ( r'<STR_LIT>' ) <EOL> for backend in settings . DATABASES . values ( ) : <EOL> result = first_package_re . findall ( backend [ '<STR_LIT>' ] ) <EOL> if result and result != '<STR_LIT>' : <EOL> backend_pkg = __import__ ( result [ <NUM_LIT:0> ] ) <EOL> backend_dir = os . path . dirname ( backend_pkg . __file__ ) <EOL> paths . append ( os . path . dirname ( backend_dir ) ) <EOL> return paths <EOL> def run_test ( self , script , args , settings_file = None , apps = None ) : <EOL> project_dir = os . path . dirname ( test_dir ) <EOL> base_dir = os . path . dirname ( project_dir ) <EOL> ext_backend_base_dirs = self . _ext_backend_paths ( ) <EOL> old_django_settings_module = os . environ . get ( '<STR_LIT>' , None ) <EOL> if sys . platform . startswith ( '<STR_LIT>' ) : <EOL> python_path_var_name = '<STR_LIT>' <EOL> else : <EOL> python_path_var_name = '<STR_LIT>' <EOL> old_python_path = os . environ . get ( python_path_var_name , None ) <EOL> old_cwd = os . getcwd ( ) <EOL> if settings_file : <EOL> os . environ [ '<STR_LIT>' ] = settings_file <EOL> elif '<STR_LIT>' in os . environ : <EOL> del os . environ [ '<STR_LIT>' ] <EOL> python_path = [ project_dir , base_dir ] <EOL> python_path . extend ( ext_backend_base_dirs ) <EOL> os . environ [ python_path_var_name ] = os . pathsep . join ( python_path ) <EOL> cmd = [ sys . executable , '<STR_LIT>' , script ] <EOL> os . chdir ( test_dir ) <EOL> out , err = subprocess . Popen ( cmd + args , <EOL> stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) <EOL> if old_django_settings_module : <EOL> os . environ [ '<STR_LIT>' ] = old_django_settings_module <EOL> if old_python_path : <EOL> os . environ [ python_path_var_name ] = old_python_path <EOL> os . chdir ( old_cwd ) <EOL> return out , err <EOL> def run_django_admin ( self , args , settings_file = None ) : <EOL> bin_dir = os . path . abspath ( os . path . dirname ( bin . __file__ ) ) <EOL> return self . run_test ( os . path . join ( bin_dir , '<STR_LIT>' ) , args , settings_file ) <EOL> def run_manage ( self , args , settings_file = None ) : <EOL> conf_dir = os . path . dirname ( conf . __file__ ) <EOL> template_manage_py = os . path . join ( conf_dir , '<STR_LIT>' , '<STR_LIT>' ) <EOL> test_manage_py = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> shutil . copyfile ( template_manage_py , test_manage_py ) <EOL> with open ( test_manage_py , '<STR_LIT:r>' ) as fp : <EOL> manage_py_contents = fp . read ( ) <EOL> manage_py_contents = manage_py_contents . replace ( <EOL> "<STR_LIT>" , "<STR_LIT>" ) <EOL> with open ( test_manage_py , '<STR_LIT:w>' ) as fp : <EOL> fp . write ( manage_py_contents ) <EOL> stdout , stderr = self . run_test ( '<STR_LIT>' , args , settings_file ) <EOL> os . remove ( test_manage_py ) <EOL> return stdout , stderr <EOL> def assertNoOutput ( self , stream ) : <EOL> "<STR_LIT>" <EOL> if sys . platform == '<STR_LIT:win32>' : <EOL> stream = [ e for e in stream . splitlines ( ) <EOL> if not e . startswith ( '<STR_LIT>' ) ] <EOL> self . assertEqual ( len ( stream ) , <NUM_LIT:0> , "<STR_LIT>" % stream ) <EOL> def assertOutput ( self , stream , msg ) : <EOL> "<STR_LIT>" <EOL> self . assertTrue ( msg in stream , "<STR_LIT>" % ( msg , stream ) ) <EOL> def assertNotInOutput ( self , stream , msg ) : <EOL> "<STR_LIT>" <EOL> self . assertFalse ( msg in stream , "<STR_LIT>" % ( msg , stream ) ) <EOL> class DjangoAdminNoSettings ( AdminScriptTestCase ) : <EOL> "<STR_LIT>" <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> class DjangoAdminDefaultSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class DjangoAdminFullPathDefaultSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class DjangoAdminMinimalSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> class DjangoAdminAlternateSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class DjangoAdminMultipleSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class DjangoAdminSettingsDirectory ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , is_dir = True ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' , is_dir = True ) <EOL> def test_setup_environ ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> app_path = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . addCleanup ( shutil . rmtree , app_path ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . exists ( app_path ) ) <EOL> def test_setup_environ_custom_template ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' ] <EOL> app_path = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . addCleanup ( shutil . rmtree , app_path ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . exists ( app_path ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( app_path , '<STR_LIT>' ) ) ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_django_admin ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> class ManageNoSettings ( AdminScriptTestCase ) : <EOL> "<STR_LIT>" <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> class ManageDefaultSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class ManageFullPathDefaultSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class ManageMinimalSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> class ManageAlternateSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertRegexpMatches ( out , expected_query_re ) <EOL> self . assertNoOutput ( err ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertRegexpMatches ( out , expected_query_re ) <EOL> self . assertNoOutput ( err ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertNoOutput ( err ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertNoOutput ( err ) <EOL> class ManageMultipleSettings ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_builtin_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_builtin_with_bad_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_builtin_with_bad_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_command_with_settings ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_custom_command_with_environment ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args , '<STR_LIT>' ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class ManageSettingsWithImportError ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings_with_import_error ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def write_settings_with_import_error ( self , filename , apps = None , is_dir = False , sdict = None ) : <EOL> if is_dir : <EOL> settings_dir = os . path . join ( test_dir , filename ) <EOL> os . mkdir ( settings_dir ) <EOL> settings_file = open ( os . path . join ( settings_dir , '<STR_LIT>' ) , '<STR_LIT:w>' ) <EOL> else : <EOL> settings_file = open ( os . path . join ( test_dir , filename ) , '<STR_LIT:w>' ) <EOL> settings_file . write ( '<STR_LIT>' ) <EOL> settings_file . write ( '<STR_LIT>' ) <EOL> settings_file . close ( ) <EOL> def test_builtin_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> class ManageValidate ( AdminScriptTestCase ) : <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_nonexistent_app ( self ) : <EOL> "<STR_LIT>" <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' ] , sdict = { '<STR_LIT>' : False } ) <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_broken_app ( self ) : <EOL> "<STR_LIT>" <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' ] ) <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_complex_app ( self ) : <EOL> "<STR_LIT>" <EOL> self . write_settings ( '<STR_LIT>' , <EOL> apps = [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> sdict = { '<STR_LIT>' : True } ) <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_app_with_import ( self ) : <EOL> "<STR_LIT>" <EOL> self . write_settings ( '<STR_LIT>' , <EOL> apps = [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] , <EOL> sdict = { '<STR_LIT>' : True } ) <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> class CustomTestRunner ( DjangoTestSuiteRunner ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> assert '<STR_LIT>' not in kwargs <EOL> super ( CustomTestRunner , self ) . __init__ ( * args , ** kwargs ) <EOL> def run_tests ( self , test_labels , extra_tests = None , ** kwargs ) : <EOL> pass <EOL> class ManageTestCommand ( AdminScriptTestCase ) : <EOL> def setUp ( self ) : <EOL> from django . core . management . commands . test import Command as TestCommand <EOL> self . cmd = TestCommand ( ) <EOL> def test_liveserver ( self ) : <EOL> """<STR_LIT>""" <EOL> address_predefined = '<STR_LIT>' in os . environ <EOL> old_address = os . environ . get ( '<STR_LIT>' ) <EOL> self . cmd . handle ( verbosity = <NUM_LIT:0> , testrunner = '<STR_LIT>' ) <EOL> self . assertEqual ( '<STR_LIT>' in os . environ , address_predefined ) <EOL> self . assertEqual ( os . environ . get ( '<STR_LIT>' ) , old_address ) <EOL> self . cmd . handle ( verbosity = <NUM_LIT:0> , testrunner = '<STR_LIT>' , <EOL> liveserver = '<STR_LIT>' ) <EOL> self . assertEqual ( os . environ [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> if address_predefined : <EOL> os . environ [ '<STR_LIT>' ] = old_address <EOL> else : <EOL> del os . environ [ '<STR_LIT>' ] <EOL> class ManageRunserver ( AdminScriptTestCase ) : <EOL> def setUp ( self ) : <EOL> from django . core . management . commands . runserver import BaseRunserverCommand <EOL> def monkey_run ( * args , ** options ) : <EOL> return <EOL> self . cmd = BaseRunserverCommand ( ) <EOL> self . cmd . run = monkey_run <EOL> def assertServerSettings ( self , addr , port , ipv6 = None , raw_ipv6 = False ) : <EOL> self . assertEqual ( self . cmd . addr , addr ) <EOL> self . assertEqual ( self . cmd . port , port ) <EOL> self . assertEqual ( self . cmd . use_ipv6 , ipv6 ) <EOL> self . assertEqual ( self . cmd . _raw_ipv6 , raw_ipv6 ) <EOL> def test_runserver_addrport ( self ) : <EOL> self . cmd . handle ( ) <EOL> self . assertServerSettings ( '<STR_LIT:127.0.0.1>' , '<STR_LIT>' ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT:127.0.0.1>' , '<STR_LIT>' ) <EOL> @ unittest . skipUnless ( socket . has_ipv6 , "<STR_LIT>" ) <EOL> def test_runner_addrport_ipv6 ( self ) : <EOL> self . cmd . handle ( addrport = "<STR_LIT>" , use_ipv6 = True ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' , ipv6 = True , raw_ipv6 = True ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" , use_ipv6 = True ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' , ipv6 = True , raw_ipv6 = True ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' , ipv6 = True , raw_ipv6 = True ) <EOL> def test_runner_hostname ( self ) : <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT:localhost>' , '<STR_LIT>' ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ unittest . skipUnless ( socket . has_ipv6 , "<STR_LIT>" ) <EOL> def test_runner_hostname_ipv6 ( self ) : <EOL> self . cmd . handle ( addrport = "<STR_LIT>" , use_ipv6 = True ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' , ipv6 = True ) <EOL> def test_runner_ambiguous ( self ) : <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . cmd . handle ( addrport = "<STR_LIT>" ) <EOL> self . assertServerSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class CommandTypes ( AdminScriptTestCase ) : <EOL> "<STR_LIT>" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_version ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT:version>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , get_version ( ) ) <EOL> def test_version_alternative ( self ) : <EOL> "<STR_LIT>" <EOL> args1 , args2 = [ '<STR_LIT:version>' ] , [ '<STR_LIT>' ] <EOL> self . assertEqual ( self . run_manage ( args1 ) , self . run_manage ( args2 ) ) <EOL> def test_help ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> def test_help_commands ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNotInOutput ( out , '<STR_LIT>' ) <EOL> self . assertNotInOutput ( out , '<STR_LIT>' ) <EOL> self . assertNotInOutput ( out , '<STR_LIT>' ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> self . assertOutput ( out , '<STR_LIT>' ) <EOL> self . assertNotInOutput ( out , '<STR_LIT>' ) <EOL> def test_help_alternative ( self ) : <EOL> "<STR_LIT>" <EOL> args1 , args2 = [ '<STR_LIT>' ] , [ '<STR_LIT>' ] <EOL> self . assertEqual ( self . run_manage ( args1 ) , self . run_manage ( args2 ) ) <EOL> def test_help_short_altert ( self ) : <EOL> "<STR_LIT>" <EOL> args1 , args2 = [ '<STR_LIT>' ] , [ '<STR_LIT>' ] <EOL> self . assertEqual ( self . run_manage ( args1 ) , self . run_manage ( args2 ) ) <EOL> def test_specific_help ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_base_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_base_command_no_label ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_base_command_multiple_label ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_base_command_with_option ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_base_command_with_options ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:x>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_noargs ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_noargs_with_args ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_app_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , os . sep . join ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_app_command_no_apps ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_app_command_multiple_apps ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , os . sep . join ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , os . sep . join ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_app_command_invalid_appname ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_app_command_some_invalid_appnames ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_label_command ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_label_command_no_label ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertOutput ( err , '<STR_LIT>' ) <EOL> def test_label_command_multiple_label ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class ArgumentOrder ( AdminScriptTestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . write_settings ( '<STR_LIT>' , apps = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . write_settings ( '<STR_LIT>' ) <EOL> def tearDown ( self ) : <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> self . remove_settings ( '<STR_LIT>' ) <EOL> def test_setting_then_option ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_setting_then_short_option ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_option_then_setting ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_short_option_then_setting ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:x>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> def test_option_then_setting_then_option ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> out , err = self . run_manage ( args ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertOutput ( out , "<STR_LIT>" ) <EOL> class StartProject ( LiveServerTestCase , AdminScriptTestCase ) : <EOL> def test_wrong_args ( self ) : <EOL> "<STR_LIT>" <EOL> out , err = self . run_django_admin ( [ '<STR_LIT>' ] ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_simple_project ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_invalid_project_name ( self ) : <EOL> "<STR_LIT>" <EOL> def cleanup ( p ) : <EOL> if os . path . exists ( p ) : <EOL> shutil . rmtree ( p ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( cleanup , testproject_dir ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> self . assertFalse ( os . path . exists ( testproject_dir ) ) <EOL> def test_simple_project_different_directory ( self ) : <EOL> "<STR_LIT>" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> os . mkdir ( testproject_dir ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" ) <EOL> def test_custom_project_template ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_template_dir_with_trailing_slash ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' + os . sep ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_custom_project_template_from_tarball_by_path ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_custom_project_template_from_tarball_to_alternative_location ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> os . mkdir ( testproject_dir ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_custom_project_template_from_tarball_by_url ( self ) : <EOL> "<STR_LIT>" <EOL> template_url = '<STR_LIT>' % self . live_server_url <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_url , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_project_template_tarball_url ( self ) : <EOL> "<STR_LIT>" <EOL> template_url = '<STR_LIT>' % self . live_server_url <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_url , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> def test_file_without_extension ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> self . assertTrue ( os . path . isdir ( testproject_dir ) ) <EOL> self . assertTrue ( os . path . exists ( os . path . join ( testproject_dir , '<STR_LIT>' ) ) ) <EOL> base_path = os . path . join ( testproject_dir , '<STR_LIT>' ) <EOL> for f in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> self . assertTrue ( os . path . exists ( os . path . join ( base_path , f ) ) ) <EOL> with open ( os . path . join ( base_path , f ) ) as fh : <EOL> self . assertEqual ( fh . read ( ) , <EOL> '<STR_LIT>' ) <EOL> def test_custom_project_template_context_variables ( self ) : <EOL> "<STR_LIT>" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> os . mkdir ( testproject_dir ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . addCleanup ( shutil . rmtree , testproject_dir ) <EOL> self . assertNoOutput ( err ) <EOL> test_manage_py = os . path . join ( testproject_dir , '<STR_LIT>' ) <EOL> with open ( test_manage_py , '<STR_LIT:r>' ) as fp : <EOL> content = fp . read ( ) <EOL> self . assertIn ( "<STR_LIT>" , content ) <EOL> self . assertIn ( "<STR_LIT>" % testproject_dir , content ) <EOL> def test_custom_project_destination_missing ( self ) : <EOL> """<STR_LIT>""" <EOL> template_path = os . path . join ( test_dir , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , template_path , '<STR_LIT>' , '<STR_LIT>' ] <EOL> testproject_dir = os . path . join ( test_dir , '<STR_LIT>' ) <EOL> out , err = self . run_django_admin ( args ) <EOL> self . assertNoOutput ( out ) <EOL> self . assertOutput ( err , "<STR_LIT>" % testproject_dir ) <EOL> self . assertFalse ( os . path . exists ( testproject_dir ) ) </s>
|
<s> from __future__ import absolute_import <EOL> from django . conf . urls import patterns , url <EOL> from . import views <EOL> urlpatterns = patterns ( '<STR_LIT>' , <EOL> ( r'<STR_LIT>' , views . request_processor ) , <EOL> ) </s>
|