Python development [Django]: logging, API authentication, pythondjango

Source: Internet
Author: User
Tags key string

Python development [Django]: logging, API authentication, pythondjango
Log record:

Call the same object to record the error log and running log respectively.

Custom log class:

Class Logger (object): _ instance = None def _ init _ (self): self. run_log_file = settings. RUN_LOG_FILE self. error_log_file = settings. ERROR_LOG_FILE self. run_logger = None self. error_logger = None self. initialize_run_log () self. initialize_error_log () def _ new _ (cls, * args, ** kwargs): # Singleton mode if not cls. _ instance: cls. _ instance = object. _ new _ (cls, * args, ** kwargs) return cls. _ instance @ staticmethod def check_path_exist (log_abs_file): log_path = OS. path. split (log_abs_file) [0] if not OS. path. exists (log_path): OS. mkdir (log_path) def initialize_run_log (self): self. check_path_exist (self. run_log_file) file_1_1 = logging. fileHandler (self. run_log_file, 'A', encoding = 'utf-8') fmt = logging. formatter (fmt = "% (asctime) s-% (levelname) s: % (message) s") file_1_1.setFormatter (fmt) logger1 = logging. getLogger ('run _ log') # 'run _ log' write logger1.setLevel (logging. INFO) # effect and logging in error. like Logger, logger1.addHandler (file_1_1) self. run_logger = logger1 def initialize_error_log (self): self. check_path_exist (self. error_log_file) file_1_1 = logging. fileHandler (self. error_log_file, 'A', encoding = 'utf-8') fmt = logging. formatter (fmt = "% (asctime) s-% (levelname) s: % (message) s") file_1_1.setFormatter (fmt) logger1 = logging. logger ('run _ log', level = logging. ERROR) logger1.addHandler (file_1_1) self. error_logger = logger1 def log (self, message, mode = True): "Write log: param message: log information: param mode: True indicates the running information, and False indicates the error message: return: "" if mode: self. run_logger.info (message) else: self. error_logger.error (message)

Call method:

If ret ['code'] = 1000: print (IP, 'updated successfully') Logger (). log (ret ['message'], True) else: Logger (). log (ret ['message'], False)

  

API authentication:

The key string + timestamp is sent for authentication. If the authentication fails after the timeout period expires, the Authenticated Key is cleared out.

Client:

Import hashlibimport timeimport requestsclass Client (object): def _ init _ (self): self. key = '299095cc-1330-11e5-b06a-a45e60bec08b' self. key_name = 'auth-key' self. asset_api = 'HTTP: // 127.0.0.1: 8000/api/'def auth_key (self): "interface authentication" ha = hashlib. md5 (self. key. encode ('utf-8') # Use self. key for encryption salt time_span = time. time () ha. update (bytes ("% s | % f" % (self. key, time_span), encoding = 'utf-8') encryption = ha. hexdigest () result = "% s | % f" % (encryption, time_span) return {self. key_name: result} def get_asset (self): "" submit asset information to the street in post mode "headers = {} headers. update (self. auth_key () response = requests. get (url = self. asset_api, headers = headers,) print (response. text) Client (). get_asset ()

Server:

From django. views import Viewimport timeimport hashlibASSET_AUTH_KEY = '299095cc-Shanghai' # Authentication Authorization = 'HTTP _ AUTH_KEY '# Authentication Header ASSET_AUTH_TIME = 2 # timeout value ENCRYPT_LIST = [] # store authenticated keydef api_auth (request): auth_key = request. META. get (ASSET_AUTH_HEADER_NAME) if not auth_key: # incorrect request Authentication Header return False sp = auth_key.split ('|') if len (sp )! = 2: # incorrect format return False encrypt, timestamp = sp timestamp = float (timestamp) # Replace str with float limit_timestamp = time. time ()-ASSET_AUTH_TIME if limit_timestamp> timestamp: # time-out comparison between the current program time and client timestamp return False ha = hashlib. md5 (ASSET_AUTH_KEY.encode ('utf-8') ha. update (bytes ("% s | % f" % (ASSET_AUTH_KEY, timestamp), encoding = 'utf-8') result = ha. hexdigest () if encrypt! = Result: # md5 value verification return False exist = False del_keys = [] for k, v in enumerate (ENCRYPT_LIST): # record the current authentication. If it has been authenticated before expiration, authentication fails, and m = v ['time'] n = v ['encrypt'] if m <limit_timestamp: del_keys.append (k) continue if n = encrypt: exist = True for k in del_keys: del ENCRYPT_LIST [k] if exist: return False ENCRYPT_LIST.append ({'encrypt': encrypt, 'time ': timestamp}) return Trueclass Api (View): def get (self, request): result = api_auth (request) if result: return HttpResponse ('authenticated successful') else: return HttpResponse ('Fuck you ')

 

  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.