How does python implement the interface?

Source: Internet
Author: User
Tags md5 encryption
Interface just defines some methods, but not to implement, more for the programming, but the design needs to what kind of function, but did not implement any function, these functions need to be inherited by another class (b), class B to implement one of these functions or all functions.

Interface Basics:

Simply say the interface test, now commonly used 2 kinds of interface is the HTTP API and RPC protocol interface, today mainly said: HTTP API interface is to go HTTP protocol through the path to distinguish the call method, request message format is Key-value form, return message is generally JSON string;

Interface protocol: HTTP, WebService, RPC, and so on.

Request method: Get, Post mode

Request parameter format:

A. Get requests are all through url?param=xxx&param1=xxx

B. Request parameters for post requests common types are: Application/json, application/x-www-form-urlencoded, Multipart/form-data, text/html, and so on.

You also need to know the URL of the interface, the parameter type, the data format of the returned result, and the information about whether the interface has headers, cookies, etc.

Interface implementation: Request mode-get, the interface of the wording:


 Import flask from flask Import request from Flask Import jsonify Import Tools import op_db Import Settings "' Flask:web Framework, can be provided by Flask @server.route () to convert the ordinary function to the service login interface, need to pass the URL, username, passwd "" #创建一个服务, the current Python file as a service server = Flask. Flask (name) #server. config[' json_as_ascii '] = False # @server. Route () can transform the normal function into the path of the service login interface, the request method @server. Route ('/login ' , methods=[' Get ']) def login (): # Gets the data via URL request parameter username = request.values.get (' name ') # Gets the password for URL request, plaintext pwd = Request. Values.get (' pwd ') # determines that the user name and password are NOT NULL, if the user name, password is not passed username and pwd is none if username and pwd: # get encrypted password Password = tools.md5_p WD (PWD) #执行sql, if the username and password of the query are not empty, the description database exists in the admin account sql = ' Select Name,password from Test where name= '%s ' and PA    ssword= "%s"; '% (username, password) # After the data query results, RES returns is a tuple res = Op_db.getconn (host=settings.mysql_info[' host '), user=settings.mysql_info[' user '], passwd=settings.mysql_info[' pwd '], db=settings.mysql_info[' db ', port=settings. mysql_info[' Port '], Sql=sql  If res: #res的结果不为空, the username=admin user was found, and password is the 123456 resu before encryption: "$, ' message ': ' Login successful '} return   Jsonify (ResU) #将字典转换为json串, JSON is the string else:resu = {' Code ':-1, ' message ': ' Account/Password error '} return jsonify (resu) Else: res = {' Code ': 999, ' message ': ' Required parameter not filled '} return jsonify (res) if name = = ' main ': Server.run (Debug=true, port=8888, H ost=0.0.0.0) #指定端口, host,0.0.0.0 representative no matter how many network cards, any IP can access

MD5 encryption, database MySQL operations see my other blogs ~~~~~

Get access interface:

After the project starts, the address of the interface is: Http://127.0.0.1:5000/, the default port is 5000.

Open the browser, enter urlhttp://127.0.0.1:5000/xxx?name=xxx&pwd=123456, followed by the address of the interface login, parameters and URL directly use? Connected, each request parameter is directly connected using &. If the request succeeds, it returns {' Code ': $, ' message ': ' Login succeeded '}.

Request method-post, interface:


 Import flask from flask import jsonify from flask Import request from Conf import opmysql from conf import md5_create "' Register interface: POST request, request parameter entry type JSON {"username": "AAA", "pwd": "123456", "c_pwd": "123456"} "" Server = Flask. Flask (name) @server. Route ('/register ', methods=[' get ', ' post ') def registerpost (): #判断接口的请求方式是GET还是POST if Request.method = = ' POST ': # GET request parameter is JSON format, return result is dictionary params = Request.json username = params.get (' username ') pwd = PA Rams.get (' pwd ') confirmpwd = Params.get (' confirmpwd ') if username and pwd and confirmpwd: # Determine the user name, password, and confirmation password are not empty SE Lect_sql = ' Select username from Lhldemo where username = '%s '; '      %username # Query whether the registered user exists in the database, if present, then username is not empty, otherwise username is empty res_mysql = Opmysql.op_select (select_sql) if Res_mysql:  Return jsonify ({"Code": 999, "MESG": "User Registered"}) else:if pwd = = confirmpwd: # Judging pwd and confirmpwd consistent new_pwd = Md5_create.md5_test (PWD) # encrypted password Insert_sql = ' INSERT INTO Lhldemo (Username,password) VALUES ("%s", "%s") ; '% (username, new_pwd) opmysql.op_insert (insert_sql) return jsonify ({"Code": $, "MSG": "Registered successfully"}) Else:  Return jsonify ({"Code": 998, "msg": "Password not the same"}) Else:return jsonify ({"Code": 504, "MSG": "Must not be Empty"}) Else:return Jsonify ({"Code": 201, "MSG": "The request is incorrect"}) if Name = = ' main ': #port可以指定端口, the default port is #host写成0.0.0.0, other people can access, on behalf of listening to multiple network cards above, The default is 127.0.0.1 Server.run (debug=true, port=8899, host= ' 0.0.0.0 ')

Post Access interface:

After the project starts, the address of the interface is: Http://127.0.0.1:5000/, the default port is 5000.

Open the browser, enter Urlhttp://127.0.0.1:5000/xxx, followed by the address register of the interface, the parameters are requested using Postman or JMeter, and the parameter type is JSON. If the request succeeds, it returns {' Code ': $, ' message ': ' Login succeeded '}.

Request Method-get, post can be accessed, the following wording:


 Import flask from flask import jsonify from flask Import request from Conf import opmysql from conf import md5_create "' Register interface: POST request, request parameter entry type JSON {"username": "AAA", "pwd": "123456", "c_pwd": "123456"} "" Server = Flask.  Flask (name) @server. Route ('/register ', methods=[' get ', ' post ') def registerpost (): #post请求获取请求的参数, the returned result type is str Username = request.values.get (' username ') pwd = request.values.get (' pwd ') confirmpwd = Request.values.get (' confirmpwd ') If username and pwd and confirmpwd: # Determine that the user name, password, and confirmation password entered are not empty select_sql = ' Select username from Lhldemo where username = "%s"; '    %username # Query whether the registered user exists in the database, if present, then username is not empty, otherwise username is empty res_mysql = Opmysql.op_select (select_sql) if Res_mysql: Return jsonify ({"Code": 999, "MESG": "User Registered"}) else:if pwd = = confirmpwd: # Judging pwd and confirmpwd consistent new_pwd = MD5_CR Eate.md5_test (PWD) # encrypted password Insert_sql = ' INSERT INTO Lhldemo (Username,password) VALUES ("%s", "%s"); '% (username, NE     W_PWD) Opmysql.op_insert (insert_sql)Return jsonify ({"Code": $, "MSG": "Registered Successfully"}) Else:return jsonify ({"Code": 998, "msg": "Password not the same"}) Else:return JS Onify ({"Code": 504, "MSG": "Must not be empty"}) if Name = = ' main ': #port可以指定端口, the default port is the #host默认是127.0.0.1, written 0.0.0.0 words, other people can visit, Represents listening on multiple NICs above, Server.run (Debug=true, port=8899, host= ' 0.0.0.0 ')

Post requests can be made in 2 ways, one of the following:

Stitching parameters via URL:

The second way to access: through the Key-value way to access:

For Redis-related operations, add the value of the hash type to the Redis, the interface is implemented as follows:


Import flask from flask import jsonify from conf import Opredis from flask import Request "Redis add data, the type of deposit data is hash type, format as Under: POST request, request parameter entry parameter type JSON {name:{"key": "Value"}} {"username": "url"} ' "Server = flask. Flask (name) @server. Route ('/set_sties ', Methods =[' Post ') def set_sties ():  # Get URL request parameter, return result is dictionary {"username": "Byz" , "url": "Http://www.baidu.com"}  res_dic = Request.json  if Res_dic.get (' username ') and res_dic.get (' URL '):   username = res_dic.get (' username ')   url = res_dic.get (' url ')   #调用redis的hset方法, storing username, url into Redis   Opredis.get_hashall (' sites ', username, url)   return jsonify ({"Code":)  Else:   return jsonify ({"Code": 204, "MSG": "must not be blank"})  if name = = ' main ':  #port可以指定端口, the default port is  #host默认是127.0.0.1, Written 0.0.0.0 words, other people can access, on behalf of listening to multiple network cards above,  Server.run (Debug=true, port=8899, host= ' 0.0.0.0 ')

The hash type structure is as follows:

{Name:{key,value}}, after the interface has been successfully accessed, the data storage structure in Redis is as follows:

After Redis adds the data, it reads the data inside the Redis, and the interface is implemented as follows:


Import flask from flask import jsonify to conf import Opredis from flask import Request ' ' to read data within Redis, Redis datastore type is hash Type, formatted as follows {name:{"key": "Value"}} Idea: 1. The Redis Hgetall (name) method reads all Redis data, and the returned result type is Dictionary  2. Loop the contents of the dictionary, converting the element type to STR, and store the results in the dictionary "server = Flask." Flask (name) @server. Route ('/get_sties ', Methods =[' get ', ' post ') def get_sties ():  #获取redis内所有的数据信息, the returned result type is a dictionary, The inside element is the bytes type, name=sites  dic = Opredis.get_hashall (' sites ')  redislist = []  for key, value in Dic.items ():   redis_dic = {}   #将字典内元素的类型由bytes转换为str   k = Key.decode ()   v = value.decode ()   #字典redis_dic内结构 {" username:k, "url": v}   redis_dic[' username ') = k   redis_dic[' url '] = v   redislist.append (redis_dic)  return jsonify ({"Code": $, "MSG": Redislist})  if name = = ' main ':  #port可以指定端口, the default port is  Host default is 127.0.0.1, written 0.0.0.0 words, other people can access, on behalf of listening to multiple network cards above,  Server.run (Debug=true, port=8899, host= ' 0.0.0.0 ')

With the Postman method interface, the returned data is as follows:

To query the user, you need to pass the token value, the implementation method is as follows:

Login interface:


Import flask from flask import jsonify from conf import opredis from conf import opmysql from conf import md5_create from Flask Import Request Import time ' login interface, need to pass the user name, password, query the database to determine whether the user is successful login, if the login is successful, the user name and token into Redis ' server = flask. Flask (name) @server. Route ('/login ', methods=[' get ', ' post ') def set_cookies ():  name = Request.values.get (' Username ')  pwd = request.values.get (' pwd ')  if Name and pwd:   #加密后的密码   new_pwd = md5_create.md5_test (pwd )   sql = ' Select Username,password from Lhldemo where username= '%s ' and password= '%s '; '% (name, new_pwd)   res_sql = opmysql.op_select (sql)   if res_sql:    token = name + time.strftime ('%y%m%d%h%m%s ') )    New_token = md5_create.md5_test (token)    #用户登录成功后, put name and token into Redis, and the data type is hash type    opredis.get_ Hashall (' user ', name, New_token)    return jsonify ({"Code": +})   else:    return jsonify ({"Code": 204})  else:   return jsonify ({"Code": 304})

To query the user, you need to pass the user name and token value, the implementation method is as follows:


 Import flask from flask import jsonify from conf import opredis from conf import opmysql from conf import md5_create from Flask Import Request Import time ' login interface, need to pass the user name, password, query the database to determine whether the user is successful login, if the login is successful, the user name and token into Redis ' server = flask. Flask (name) @server. Route ('/search_user ', methods=[' get ', ' post ') def set_cookies (): name = Request.values.get ('   Username ') token = request.values.get (' token ') print (' token ', token) if name and token: #查看数据库 to see if the queried user exists and returns the user ID if it exists sql = ' Select id from Lhldemo where username= '%s '; '% (name) Res_sql = opmysql.op_select (sql) if res_sql: #从redis中获取user下的用户名对应的token值 res_token = Opredis.getredi S (' User: ' +name) if Res_token = = Token:return jsonify ({"MSG": "User ID", "id": res_sql}) Else:return jsonify  ({"MSG": "Token Error"}) Else:return jsonify ({"Code": "User does not Exist"}) Else:return jsonify ({"Code": "Must not be empty"}) if Name = = ' Main ': #port可以指定端口, the default port is the #host默认是127.0.0.1, written 0.0.0.0 words, other people can access, on behalf of listening to multiple network cards above, Server.run (Debug=true, POrt=8899, host= ' 0.0.0.0 ') 

above is commonly used in the work of a number of interface scenarios, testing payment related interfaces, or third-party interfaces, you can self-mock interface return FALSE data operation ~ ~ ~

Related Article

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.