python开发网络知识01

常用的HTTP头字段
字段名 方向 解释 可能的值
Accept Request 接收什么介质类型 type/sub-type */*表示任何类型,type/*表示该类型下的所有子类型
Accept-Charaset Request 接收的字符集 IOS-8859-1
Accept-Encoding Request 接收的编码方法,通常指定压缩方法,是否支持压缩,支持什么压缩方法 Gzip,deflate,UTF8
Accept-Language Request 接收的语言 En、cn
Accept-Ranges Request 服务器表明自己是否接受获取其某个实体的一部分(比如文件的一部分)的请求 bytes:表示接受 none:表示不接受
Age Response 用该头部表明该实体从产生到现在经过多长时间
Authorization Response 当客户端接收来自Web服务器的WWW-Authenticate响应时,该头部回应自己的身份验证信息给Web服务器 Username:password
Cache-Control Request 对服务器的缓存控制 no-cache:不要从缓存中去取,要求现在从Web服务器去取
Cache-Control Response 对客户端的缓存控制 public:可以用缓存内容回应任何用户。private:只能用缓存内容回应先前请求该内容的那个用户
Connection Request 对服务器的连接控制 Close:告诉web服务器在完成本次请求的响应后,断开连接,不要等待本次连接的后续请求了,Keepalive:连接保持,等待本次连接的后续请求
Connection Response 连接状态通知 Close:连接已关闭 Keepalive:连接保持,等待本次连接的后续请求
Etag Both 内容的唯一标识。客户端需要把服务器传来的ETag保留,在下次请求相同的URL时提交给服务器。服务器用Etag值判断同一个URL的内容是否有变化,如有变化则发送更新的内容给客户端
Expried Response web服务器表明该实体将在什么时候过期 YYYY-MM-DD HH:MM:SS
Host Request 客户端指定自己想访问的WEB服务器的域名,ip地址和端口号 ip:port
Location Response 访问的对象已经被移到别的位置了,应该到本头字段指向的地址获取 hhtp://mysit.com/another_url
Proxy-Authenticate Response 代理服务器响应浏览器,要求其提供代理身份验证信息
Proxy-Authenticate Request 提供自己在代理服务器中的身份信息 Username:password
range Request 需要获取对象的哪一部分内容 bytes=1024-:获取从第1024个字节到最后的内容
Referer Request 浏览器想web服务器表明自己是从哪个URL获得当前请求中的URL的 http://www.baidu.com
Server Response 指明服务器的软件类型及版本 Nginx/1.14
User-Agent Request 指明浏览器的软件类型及版本 Mozilla/x.x windows浏览器 Firefor/xx.x.x
Via Both 列出从客户端到服务器或者相反方向的响应

HTTP状态码
1xx:信息,表明服务器已经收到Request,但需要进一步处理,请客户端等待
2xx:成功
3xx:重定向;请求的地址已经被重定向,需要客户端重新发起请求
4xx:客户端错误,请求中提交的参数获内容有错误
5xx:服务端错误,服务器处理请求时出错,一般本类错误需要联系服务器管理员处理

Use Python script to comply sqlldr’s tool auto

The CSV file that use python script was output.The CSV file was loaded the oracle database.
we will use the sqlldr tools comply the function.

NOTE:
1.csv file format ,for example:xxxx-yyyymmdd.csv
2.os env:linux,don't fit the windows
3.the python script at the oracle database server machine.
4.configure the python on the oracle database server machine


# -*- coding: utf-8 -*-
"""
Created on Thu Nov 24 17:04:34 2016

@author: trsenzhang
"""

import os 
import sys
import time

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
#python script directory
CUR_PATH = os.path.dirname(os.path.realpath(__file__))

def sed(type,filename="",s_str="",d_str=""):  
  '''
  a behind the "s_str" line append "d_str". if "s_str" is null, then append in the end of the file;
  i in front of "s_str" line append "d_str". if "s_str" is null,then append in the header of the;
  d  delete the "s_str" line 
  s replace string of "s_str" to "d_str"
  '''

  fp = open(filename)
  cont = fp.read()
  fp.close()
  content = cont.split("\n")
  content2 = cont.split("\n")
  cnt = 0
  idx = 0
  if type == 'a':
      if not s_str:
          content.append(d_str)
      else:
          for i in content2:
              if i.find(s_str) != -1:
                  x = idx + 1 + cnt
                  content.insert(x,d_str)
                  cnt += 1
              idx += 1
  elif type == 'i': 
      if not s_str: 
          content.insert(0,d_str)
      else:  
          for i in content2: 
              if i.find(s_str) != -1:  
                  x = idx + cnt  
                  content.insert(x,d_str)  
                  cnt += 1 
              idx += 1 
  elif type == 'd':  
      for i in content2:  
          if i.find(s_str) != -1:  
              idx = content.remove(i)  
  elif type == 's':
      cont=str.replace(cont,s_str,d_str)
      content=cont.split("\n")
  fp = open(filename, "w")  
  fp.write("\n".join(content))  
  fp.close()

def getSqlldir():            
    ctlfile=CUR_PATH+'/sqlldir/orders.ctl'
    csvfile1=CUR_PATH+'/report/Orders-'+str(int(time.strftime("%Y%m%d",time.localtime()))-2)+'.csv'
    csvfile2=CUR_PATH+'/report/Orders-'+str(int(time.strftime("%Y%m%d",time.localtime()))-1)+'.csv'
    sqllogfile=CUR_PATH+'/sqlldir/log/Orders_sqlldir_'+str(int(time.strftime("%Y%m%d",time.localtime()))-1)+'.log'
    badfile=CUR_PATH+'/sqlldir/log/Orders_sqlldir_'+str(int(time.strftime("%Y%m%d",time.localtime()))-1)+'.bad'
    #modify the sqlldr controlfile    
    sed('s',ctlfile,csvfile1,csvfile2)
    #load the csv to oracle database.
    os.system('/u01/app/oracle/product/11.2.0/dbhome_1/bin/sqlldr system/oracle control='+ctlfile+' log='+sqllogfile+' bad='+badfile+' skip=1')

if __name__ == '__main__':
    if not os.path.exists('%s/sqlldir' % CUR_PATH):
        os.mkdir('%s/sqlldir' % CUR_PATH)
  if not os.path.exists('%s/sqlldir/log' % CUR_PATH):
              os.mkdir('%s/sqlldir/log' %s CUR_PATH):
    getSqlldir()

Python Achieve Encryption and Decryption

    Security is a very important topic.Using python programe processing data in the database maybe need to encrypt and decrpypt.
    Today,we provid the way that use the md5 algorithm. the coding as follows:    
    we can only study Crypto.Cipher module of AES and Random
    
# sudo pip install pycrypto 
from Crypto.Cipher import AES
from Crypto import Random

BS = 16
pad = lambda s: s + (BS – len(s) % BS) * chr(BS – len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
#32 bit key
key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

class AESCipher:
    def __init__(self):
        """
        Requires hex encoded param as a key
        """
        self.key = key.decode("hex") 
        self.cipher = AES.new(self.key,AES.MODE_ECB)

    def encrypt( self, string):
        """
        Returns hex encoded encrypted value!
        """
        encrypted_string = string
        try:
            raw = pad(string) 
            encrypted_string = self.cipher.encrypt(raw).encode('hex')
            encrypted_string = encrypted_string.upper()
        except Exception as e:
            pass        
        return encrypted_string

    def decrypt( self, encrypted_string ):
        """
        Requires hex encoded param to decrypt
        """
        decrypted_string =encrypted_string
        try:
            decrypted_string = unpad(self.cipher.decrypt(encrypted_string.decode('hex')))
        except Exception as e:
            pass        
        return decrypted_string

if __name__ == '__main__'
    aes = AESCipher()
    ….
    


 

Study python of day1

"""
require:user login and verify user information on login user information file. If not ,after the three
attempt to lock the user.if enter username on black user information file,then printing the "user locked".
if username and password is right, then print "success".
define login user  and black user information file.
@trsenzhang
"""

import os
import sys

#define variable
account_file = 'D:/study_python/day1/match.txt'
account_name = 'match.txt'
lock_file = 'D:/study_python/day1/lock.txt'
lock_name='lock.txt'

def file_exists(a,b):
    if os.path.exists(a):
        print("The  file %s is exist" %b)
    else:
        account_name = open(b,"w")
        account_name.close()

def deny_account(username):
    print("your account was locked!!!")
    with open(lock_file,'a') as deny_f:
        deny_f.write('\n'+username)

def main():

    #determine the acount is or not locked
    file_exists(account_file, account_name)
    file_exists(lock_file, lock_name)

    #define variable
    retry_count = 0
    retry_limit = 3

    #determine the login in times
    while retry_count < retry_limit:
        username = input("please input your name :[]\n")
        with open(lock_file,'r') as lock_f:
            for line in lock_f.readlines():
                if len(line) == 0:
                    continue
                if username == line.strip():
                    print("The %s is locked" %username)
                    sys.exit()
        if len(username) == 0:
            print("The username is not null,please input yourname account name")
            continue

        pwd = input("please input your password :[]\n")
        with open(account_file,'r') as account_f:
            flag = False
            for line in account_f.readlines():
                user,pd = line.strip().split()
                if username == user and pwd == pd:
                    print("you are success!!")
                    print("welcome your %s" %username)
                    flag = True
                    break
        if flag == False:
            if retry_count <2:
                print("please input your password too!")

            retry_count += 1

        else:

            break
    else:
        deny_account(username)

if __name__ == '__main__':
    main()