Python Note 8: requests module, pythonrequests

Source: Internet
Author: User

Python Note 8: requests module, pythonrequests
Introduction:

Requests is an http client library of python. Similar to urlib and urlib2, the requests module is developed based on the urlib module and its code implementation is more concise.

Module installation:

Pip install requests. You can directly import requests when using the requests module.

Simple use of requests:

For http interfaces, request methods are divided into get and post, which are the most commonly used. Common Request Parameters include key-value, json, file upload, and cookies and headers.

Get request-url merging parameters:
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/gettest? Username = abc' # The returned result type is string: {"msg": "pass"} res = requests. get (url). text

You can also use. json (). The returned result type is a dictionary (note: the return value type of an Interface request is related to the return definition type of the interface)

# The returned result type is dictionary: {'msg ': 'pass'} res_dic = requests. get (url). json ()
Get request-the request parameter type is in the key-value format:
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/gettest' # Set the parameter type to name = xxx & pwd = 123456 data = {"username ": "abc"} # The returned result type is str: {"msg": "pass"} res = requests. get (url, data ). text

You can also use. json (). The returned result type is a dictionary (note: the return value type of an Interface request is related to the return definition type of the interface)

# The returned result type is dictionary: {"msg": "pass"} res_dic = requests. get (url, data). json ()
The get request interface is implemented as follows:
1 import flask 2 from flask import request 3 from flask import jsonify 4 5 server = flask. flask (_ name _) 6 @ server. route ('/gettest', methods = ['get']) 7 def test1 (): 8 name = request. values. get ('username') 9 if name = 'abc': 10 # the return value type of the API is dictionary 11 res = {"msg": "pass"} 12 return jsonify (res) 13 else: 14 res = {'msg ': "fail"} 15 return jsonify (res) 16 server. run (debug = True)
View Codepost request-url merging Parameters
Import requestsimport jsonurl = 'HTTP: // 127.0.0.1: 5000/gettest? Username = abc' # The returned result type is str: {"msg": "pass"} res = requests. post (url ). text # json. loads converts a string (json string) to a dictionary type to facilitate the operation of res_dic = json. loads (res)

You can also use. json (). The returned result type is a dictionary (note: the return value type of an Interface request is related to the return definition type of the interface)

# The returned result type is dictionary: {'msg ': 'pass'}. The dictionary Value Comparison Method is res_dic = requests. post (url). json ()
Post request-the parameter type is in the key-value format
Import requestsimport jsonurl = 'HTTP: // 127.0.0.1: 5000/gettest? Username = abc 'data = {"username": "abc"} # The returned result type is str: {"msg": "pass"} res = requests. post (url, data ). text # json. loads converts a string (json string) to a dictionary type to facilitate the operation of res_dic = json. loads (res)

You can also use. json (). The returned result type is a dictionary (note: the return value type of an Interface request is related to the return definition type of the interface)

# The returned result type is dictionary: {'msg ': 'pass'}. The dictionary Value Comparison Method is res_dic = requests. post (url, data). json ()
The implementation of the post request interface is as follows:
1 import flask 2 from flask import request 3 from flask import jsonify 4 5 server = flask. flask (_ name _) 6 @ server. route ('/gettest', methods = ['post']) 7 def test1 (): 8 # request. values. get ('xxx') is a way to obtain Request Parameters. You can access the interface through url concatenation parameters and key-value. 9 name = request. values. get ('username') 10 if name = 'abc': 11 # the return value type of the API is dictionary 12 res = {"msg": "pass"} 13 return jsonify (res) 14 else: 15 res = {'msg ': "fail"} 16 return jsonify (res) 17 server. run (debug = True)
View Code post request-the parameter type is json
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/register 'data = {"username": "admin", "pwd": "123456", "c_pwd ": "123456"} # parameter passing in json type. When requesting a post interface, you must specify that the request parameter is of the json type. The returned result is in the dictionary: {'msg ': 'OK'} res = requests. post (url, json = data ). json () print (type (res), res)
Post request-the parameter type is json, with multiple layers of json nesting
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/register 'data = {"username": "admin", "pwd": "123456", "c_pwd ": "123456", "items": {"id": 1, "age": 18, "sex": "man" }}# passing parameters of the json type, for a post Interface request, specify that the request parameter is of the json type and the returned result is: {'msg ':' OK '} res = requests. post (url, json = data ). json ()
The json parameter passing interface called by the post request. The code is implemented as follows:
1 import flask 2 from flask import request 3 from flask import jsonify 4 5 server = flask. flask (_ name _) 6 @ server. route ('/register', methods = ['post']) 7 def test1 (): 8 # request. json: the input parameter type is json. The returned result type is dictionary: {'pwd': '000000', 'username': 'asdf ', 'c _ pwd ': '000000'} 9 res_dic = request. json10 username = res_dic.get ('username') 11 pwd = res_dic.get ('pwd') 12 c_pwd = res_dic.get ('C _ pwd') 13 if username and pwd and c_pwd: 14 if res_dic.get ('username') = 'admin': 15 if res_dic.get ('pwd') = res_dic.get ('C _ pwd '): 16 return jsonify ({'msg ': "OK"}) 17 else: 18 return jsonify ({'msg': "inconsistent passwords"}) 19 else: 20 return jsonify ({'msg ': "username cannot be registered"}) 21 server. run (debug = True)
View Codepost request-upload a file
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/upload' # upload interface request data, specify the File upload path data = {"file_name": open ('e: /python_workspace/base-code/asdf.txt ', encoding = 'utf8')} # For post requests, the request parameter type is file, and the returned result type is res = requests. post (url, files = data ). json () print (type (res), res)
The Code Implementation of the upload interface called by the post request is as follows:
1 import flask 2 from flask import request 3 from flask import jsonify 4 import time, OS 5 from flask import send_from_directory 6 # Upload File interface 7 server = flask. flask (_ name _) 8 @ server. route ('/upload', methods = ['post']) 9 def upload (): 10 # Get request parameters. The parameter type is file, and the returned result type is an object: <class 'werkzeug. datastructures. filestore'> <FileStorage: 'New file .txt '('text/plain')> 11 file = request. files. get ('file _ name', None) 12 # judge whether the file is empty. if it is empty, no file is uploaded. 13 if file: 14 cur_time = time. strftime ('% Y % m % d % H % M % s') # Get the current time 15 upload_name = file. filename # obtain the name of the uploaded file 16 new_file_name = cur_time + upload_name # rename the file to prevent duplicate files from overwriting 17 # Save the file and specify the file Upload path 18 file. save ('e:/python_workspace/base-code/'+ new_file_name) 19 return jsonify ({"code": "OK"}) 20 else: 21 return jsonify ({"code": "Upload File"}) 22 23 if _ name _ = '_ main _': 24 server. run (debug = True)
View Codepost request-add cookies
Import requestsurl = 'HTTP: // 127.0.0.1: 5000/set_cookies 'data = {"username": "xiaobai", "monkey ": "999"} # request cookie parameter cookie = {"token": "123456"} # API request. The returned result type is dictionary: {'msg ': 'OK'} res = requests. post (url, data = data, cookies = cookie ). json () print (type (res), res)
THE post request calls the Add cookie interface. The code implementation is as follows:
1 import flask 2 from flask import request 3 from flask import jsonify 4 server = flask. flask (_ name _) 5 @ server. route ('/set_cookies', methods = ['post']) 6 def set_cookies (): 7 print ('obtained cookie: ', request. cookies) # {'Token': '000000'} 8 print ('requested request data: ', request. values) # CombinedMultiDict ([ImmutableMultiDict ([]), ImmutableMultiDict ([('monkey', '20140901'), ('username', 'xiaobai')]) 9 token = request. cookies. get ('Token') 10 if token: 11 return jsonify ({"msg": "OK"}) 12 else: 13 return jsonify ({"msg ": "No cookie added"}) 14 15 if _ name _ = '_ main _': 16 server. run (debug = True)
View Code post request-add headers
Import requestsheader_url = 'HTTP: // 127.0.0.1: 5000/set_headers' data = {"username": "123456", "monkey ": "666"} # Add header information header = {'content-type': "application/json"} # Interface request res = requests. post (header_url, data, headers = header ). json ()

Welcome to comments ~~~

 

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.