A, flask
flask is a lightweight framework written in python, you can use it to implement a website, web services.
Development interface with flask process:
1, a server is defined
= flask.Flask Server ( __name__ ) # __name__ represent the current python file. The current python file as a service to start
2, then the difference between the definition of the interface functions, interface functions and general function that is defined as above special function interface to add:
@ Server.route ( '/ index', methods = [ 'get', 'post']) # The first parameter is the path, supported by the second request mode parameter, then the default is not written get
server.route @ ( ' / index ' , Methods = [ ' GET ' , ' POST ' ]) # The first parameter is the path, supported by the second request mode parameter, then the default is not written GET DEF index (): RES = { ' MSG ' : ' this is the first developed excuse me ' , ' msg_code ' : 0} return json.dumps (RES, ensure_ascii = False)
3, let the server to implement
server.run (Port = 7777, Debug = True, Host = ' 0.0.0.0 ' ) # Port customizable form. Not with the machine occupied port conflict. # Debug = True, after the code is modified, the program will automatically reload, do not run again. Is run once, even if the code changes, do not need to restart the service # Host local ip address, write 0.0.0.0, you can let other people direct access to the ip of the machine. # Ultimate access to the address of the interface is http://127.0.0.1/index, get post method or methods can be. The data is the json format res content
Example:
Import the Flask, json Server = flask.Flask ( __name__ ) # __name__ represent the current python file. The current python file as a service starts @ server.route ( ' / index ' , Methods = [ ' GET ' , ' POST ' ]) # The first parameter is the path, the second argument to support the request method, do not write if default is GET DEF index (): RES = { ' msg ' : ' this is the first excuse I developed ' , ' msg_code ' : 0} return json.dumps (RES, ensure_ascii = False) server.run (Port=7777,debug=True,host='0.0.0.0')
Interface to access, often require input parameters. So if you want to accept the incoming parameters, the available methods: username = flask.request.values.get ( 'username')
Example:
Import the Flask, json Server = flask.Flask ( __name__ ) # __name__ represent the current python file. The current python file as a service starts @ server.route ( ' / REG ' , Methods = [ ' POST ' ]) # only function with the @ server.route (), this function is an interface that is not an ordinary functions DEF REG (): username = flask.request.values.get ( ' username ' ) the passwd = flask.request.values.get ( ' the passwd ' ) IF username and the passwd: SQL = 'select * from my_user where username="%s";'%username print(sql) if my_db(sql): res={'msg':'用户已存在','msg_code':2001} else: insert_sql='insert into my_user (username,passwd,is_admin) values ("%s","%s",0);'%(username,passwd) my_db(insert_sql) res={'msg':Successful registration'' , ' Msg_code ' : 0} the else : RES = { ' MSG ' : ' required field is missing, view the interface document ' , ' msg_code ' : 1001} # 1001 indicates a required interface is not filled return json.dumps (RES , ensure_ascii = False) server.run (port = 7777, Debug = True, Host = ' 0.0.0.0 ' ) # port does not write default 5000.debug = True representation changed without restarting the code will automatically help you restart. host write 0.0.0.0, others can access via ip interface. Otherwise, it is 127.0.0.1
Two, cookie handling operations
Interface login suppose to do when you want to add to the local cookie, you will need to json string returned interface to do some actions:
flask.make_response = RES (json_res) # json_res is the interface to return the data. Then json_res doing the operation, configured to return a result object res.set_cookie (Key, session_id, 3600) # The last number is the cookie expiration time. After this set, the login interface to perform successfully logged in, it will simultaneously join cookie locally. And wherein the key value is defined according to the actual session_id
Example:
@server.route('/login',methods=['get']) def login(): username = flask.request.values.get('username') pwd = flask.request.values.get('pwd') if username == 'zy' and pwd=='123456': session_id = tools.my_md5(username+time.strftime('%Y%m%d%H%M%S')) key = 'txz_session: S% ' % username tools.op_redis (Key, session_id, 600 ) RES = { ' session_id ' : session_id, ' ERROR_CODE ' : 0, ' MSG ' : ' login success ' , ' login_time ' : The time.strftime ( ' the Y m% D%%%% m% S H ' )} # returned to the user information json_res = json.dumps (RES, ensure_ascii = False) # returns the result has brought JSON RES = Flask. make_response (json_res) # configured to return the result object res.set_cookie (Key, session_id, 3600) # The last number is the cookie expiration time. return RES
The above operation can be successfully saved to a local cookie. After the interface requires the use of coookie time, just get:
= flask.request.cookies Cookies # All cokies, is a dictionary. You may then be obtained by the corresponding cookie dictionary, and performs an operation
Example: when doing some operations, it may be, this time we can directly take the content and the content server when the cookie to log on locally logged in to compare, if there is a consistent, indicating that it has successfully logged
server.route @ ( ' / Posts ' ) DEF Posts (): Cookies = flask.request.cookies # All cokies username = '' # the session = '' # define these two variables in order to, at the time did not pass the cookie use. for Key, value in cookies.items (): IF key.startswith ( ' txz_session ' ): # Analyzing beginning txz_session cookie, then take it to the username = Key the session = value # call interface when a user is passed through as seesion, from cookie inside to take over = tools.op_redis redis_session (username) # acquired from the inside to the redis Cookie IF redis_session == session: # determination seeion pass over the same session and redis inside the title flask.request.values.get = ( ' title ' ) # Gets the article title conent = flask.request.values.get ( ' content ' ) # get article content article_key = ' article:% S ' % title # Key are beginning to article tools.op_redis (article_key, conent) # to write articles Redis RES = { ' MSG ' :' Article was published successfully! ' , ' Code ' : 0} the else : RES = { ' MSG ' : ' user is not logged! ' , ' Code ' : 2009 } return json.dumps (RES, ensure_ascii = False)