Examples of implementations of interfaces in Python

Source: Internet
Author: User

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, The return message is usually a 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.

Implementation of the interface:

Request method-get, interface:

 1 Import flask 2 from Flask import request 3 from Flask import jsonify 4 Import Tools 5 Import op_db 6 import Settin GS 7 "8 flask:web frame, can be provided by Flask @server.route () to the ordinary function to the Service 9 login interface, need to pass the URL, username, passwd" "One #创建一个服务, the current p Ython 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 is @server. R     Oute ('/login ', methods=[' get ']) + def login (): 18 # Get data via URL request for parameters, username = request.values.get (' name ') 20 # Get URL request pass password, plaintext pwd = request.values.get (' pwd ') 22 # To determine the user name, password is not NULL, if the user name, password is not passed username and pwd to none if the user Name and Pwd:24 # gets the encrypted password after password = tools.md5_pwd (pwd) #执行sql, if the username and password of the query are not empty, say sql = ' Select Name,password from Test where name= '%s ' and password= '%s ' are present in the database, '% (username, password ) 28 # After the data query results, RES return is a tuple of res = Op_db.getconn (host=settings.mysql_info[' host '),user=settings.mysql_info[' user '], passwd=settings.mysql_info[' pwd ', Db=setti ngs.mysql_info[' db '], port=settings.mysql_info[' Port ', sql=sql) PNS if R             ES: #res的结果不为空, the user who found the username=admin, and password for the 123456 before encryption resu = {' Code ': $, ' message ': ' Login successful '} 39 Return jsonify (ResU) #将字典转换为json串, JSON is the string else:41 resu = {' Code ':-1, ' message ': ' Account /Password error '} jsonify (resu) else:44 res = {' Code ': 999, ' message ': ' Required parameter not filled '} Eturn jsonify (res) if __name__ = = ' __main__ ': Server.run (Debug=true, port=8888, host=0.0.0.0) #指定端口, host, 0.0.0.0 represents 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:

 1 Import flask 2 from flask import jsonify 3 from Flask Import request 4 from conf import opmysql 5 from Conf import Md5_create 6 "7 registered Interface: 8 POST request, request parameter type JSON 9 {" username ":" AAA "," pwd ":" 123456 "," c_pwd ":" 123 456 "+" "Server = Flask. Flask (__name__) @server. Route ('/register ', methods=[' GET ', ' POST ') + def registerpost (): #判断接口的请求方式是GET还是POST if Request.method = = ' POST ': 20 # Gets the request parameter is in JSON format, the returned result is a dictionary of params = Request.json Usernam         E = Params.get (' username '), pwd = Params.get (' pwd '), confirmpwd = Params.get (' confirmpwd ') 25 If username and pwd and confirmpwd: # Determine the user name, password, and confirmation password you entered are not empty. Select_sql = ' Select username from Lhldemo whe Re username = "%s"; ' %username 27 # 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 (sele Ct_sql) If res_mysql:30 return jsonify ({"Code": 999, "MESG":" User Registered "}) else:32 if pwd = = confirmpwd: # Judging pwd and confirmpwd consistent W_pwd = Md5_create.md5_test (pwd) # encrypted password after insert_sql = ' insert INTO Lhldemo (Username,password) Val UEs ("%s", "%s"); '% (username, new_pwd) opmysql.op_insert (insert_sql) retur N jsonify ({"Code": $, "MSG": "Registered Successfully"}) PNs else:38 return jsonify ({"Code": 998, "MSG": "Password not the same"}) else:40 return jsonify ({"Code": 504, "MSG": "Must not be Empty"}) else:42 return J Sonify ({"Code": 201, "MSG": "The request is incorrect"}) if __name__ = = ' __main__ ': #port可以指定端口, the default port is #host写成0.0.0 .0 words, 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: 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:

 1 Import flask 2 from flask import jsonify 3 from Flask Import request 4 from conf import opmysql 5 from Conf import Md5_create 6 "7 registered Interface: 8 POST request, request parameter type JSON 9 {" username ":" AAA "," pwd ":" 123456 "," c_pwd ":" 123 456 "+" "Server = Flask. Flask (__name__) @server. Route ('/register ', methods=[' get ', ' post ') + def registerpost (): #post请求获取请求的参数, return result type is str username = request.values.get (' username ') pwd = request.values.get (' pwd ') confirmpwd = REQUEST.V  Alues.get (' confirmpwd ') if username and pwd and confirmpwd: # Determine that the username, password, and confirmation password entered are not empty. Select_sql = ' Select Username from Lhldemo where username = "%s"; ' %username 24 # Query whether the registered user exists the database, if present, then username is not empty, otherwise username is empty res_mysql = Opmysql.op_select (select_sql) If Res_mysql:27 return jsonify ({"Code": 999, "MESG": "User Registered"}) else:29 if PWD = = confirmpwd: # Judging pwd and confirmpwd consistent with 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 ({" C Ode ": $," MSG ":" Registered Success "}) else:35 return jsonify ({" Code ": 998," msg ":" Password not the same "}) se:37 return jsonify ({"Code": 504, "MSG": "Required fields cannot be empty"}). If __name__ = = ' __main__ ': #port可以指定端口, default The port is a #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 ')

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:

1 Import flask 2 from flask import jsonify 3 from conf import Opredis 4 from Flask import Request 5 "' 6 Redis Add data, save The type of the data entered is the hash type, in the following format: 7 POST request, request parameter type JSON 8 {name:{"key": "Value"}} 9 {"username": "url"} ten "" one server = Flask. Flask (__name__) @server. Route ('/set_sties ', Methods =[' Post ') def set_sties (): 14 # Gets the URL request parameter and returns the result is the 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方法, will username         , url credited to Redis Opredis.get_hashall (' sites ', username, url) return jsonify ({"Code": +}) else:23     Return jsonify ({"Code": 204, "MSG": "Required fields cannot be empty"}) if __name__ = = ' __main__ ': #port可以指定端口, the default port is 5000 27 #host默认是127.0.0.1, written 0.0.0.0 words, other people can access, on behalf of the monitoring of 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:

 1 Import flask 2 from flask import jsonify 3 from conf import Opredis 4 from Flask import Request 5 "' 6 read the number within Redis According to the Redis data storage type is the hash type, the format is as follows 7 {name:{"key": "Value"}} 8 Ideas: 1. The Redis Hgetall (name) method reads all Redis data and returns the result type as Dictionary 9 2. Loops the contents of the dictionary, converts the element type to STR, and stores the result in a dictionary of "one server = Flask." Flask (__name__) @server. Route ('/get_sties ', Methods =[' get ', ' post ']) def get_sties (): #获取redis内所有的数据信息, returns the result class Type is the dictionary, inside the 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.deco  De () #字典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__ = = ' __ma In__ ': #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, 31 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:

 1 Import flask 2 from flask import jsonify 3 from conf import Opredis 4 from conf import opmysql 5 from conf import m D5_create 6 from Flask Import Request 7 Import time 8 "9 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 username and token will be credited to Redis within 1 0 "One 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:17 #加密后的密码 new_pwd = Md5_crea Te.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:22 token = name + time. Strftime ('%y%m%d%h%m%s ') New_token = md5_create.md5_test (token) #用户登录成功后, deposit name and token into Redis,         The deposit data type is hash type Opredis.get_hashall (' user ', name, New_token)-return jsonify ({"Code": 200}) 27 ELse:28 return jsonify ({"Code": 204}) else:30 return jsonify ({"Code": 304}) 

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

 1 Import flask 2 from flask import jsonify 3 from conf import Opredis 4 from conf import opmysql 5 from conf import m D5_create 6 from Flask Import Request 7 Import time 8 "9 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 in Redis Ten "server = Flask. Flask (__name__) @server. Route ('/search_user ', methods=[' get ', ' post '), Def set_cookies (): + name = Request.value         S.get (' username ') token = request.values.get (' token ') print (' token ', token) if name and token:18 #查看数据库, see if the queried user exists, and if so, return the user ID of sql = ' Select id from Lhldemo where username= '%s '; '% (name) Res_sql = opmysql.op_select (sql) if res_sql:22 #从redis中获取user下的用户名对应的token值 Res_token = Opredis.getredis (' User: ' +name) if Res_token = = token:27 return         Jsonify ({"MSG": "User ID", "id": Res_sql}) else:29 return jsonify ({"MSG": "Token Error"}) 30             Else:31Return jsonify ({"Code": "User does not Exist"}) else:33 return jsonify ({"Code": "Must not be empty"}) if __name__ = = ' __mai N__ ': #port可以指定端口, the default port is the PNs #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 some 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.