程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Teach you a move! Create a rest API with Python and flask!

編輯:Python

REST API brief introduction

Be careful , This is just right REST API A brief introduction , Play the role of throwing bricks and attracting jade , More in-depth content is not within the scope of this study , Interested partners can view relevant materials and learn more . In addition, we accept contributions from this field , Welcome to contact yundojun !

API

API, full name Application Programming Interface ( Application interface ), Simply speaking , It is an interface developed by the brand , Allow third parties to develop additional 、 The system communication interface applied to its own products .

REST API

REST It's a kind of passing HTTP Protocol design API Architectural style . Its main advantage is its great flexibility . As long as you need to go directly from the server to Web Users of the application or site provide data , Developers will use REST API.

REST API The main components of :

  • Customer — On user side ( On his device ) A client or program that starts communication .

  • The server — Use API A server that accesses its functions and data .

  • resources — Anything that the server transmits to the client ( video 、 Text 、 picture ).

REST API adopt HTTP Request communication , Complete the following functions —— establish 、 Read 、 Update and delete data . They are also called CRUD operation .REST Provide information about the requested resource , And use four methods to describe how to deal with resources :

  • POST — Create resources ;

  • GET — Access to resources ;

  • PUT — Update resources ;

  • DELETE — Delete resources .

RESTful API

REST, full name Representational State Transfer( Presentation layer state transition ), He is a design style ,RESTful It's just an adjective , Like peace The term peace , The adjective is peaceful,RESTful Is used to describe API, be called RESTful API.

RESTful API It mainly consists of three components :

  • Nouns Noun : Defines the location of the resource URL, Each resource will have a unique location on the network , Just as every family has a unique address .

  • Verbs Verb : What to do with resources .

  • Content Types How resources are presented :API Resources can be represented in many ways , The most common is JSON, Lightweight and easy to handle .

So use RESTful stylized API, It has the following advantages and limitations :

  1. There is only URL Indicates the resource location , A unified API Interface .(Uniform Interface)

  2. No state .(Stateless)

Restful API It allows integration of applications app Or with Restful Web Service interaction . It is now growing into the most common way to connect components in a microservice architecture . We use API, Be able to get or send data to the website and perform some operations , The purpose is to pass Web Service accomplishes our task . Each site uses different types of API, For example, the stock market trading website , With the help of API Get the current price and fluctuation .

Create the first one REST API

Again , We created Hello world API, It means that if you send get request , Will get JSON Respond to , In general , API give JSON Type of response . Next , Use pip Package manager installation Flask:

pip install flask
pip install flask-restful
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Helloworld(Resource):
  def __init__(self):
    pass
  def get(self):
    return {
      "Hello": "World"
        }
api.add_resource(Helloworld, '/')
if __name__ == '__main__':
 app.run(debug=True)

ok, The first one has been created Rest api, It looks very simple , that , What is? Flask-Restful Well ?

Flask restful Defines the resources Resource class , It contains each HTTP Method method . The method name should correspond to HTTP In the same way , And write in lowercase , As shown in the code above . We found that these methods do not have routing decorators , This is because they are based on resource routing . No matter what class is defined , We can all use add resources add_resource Method defines the route to it and calls this class on the corresponding route .

explain : In the code above , We first load the required parent class , Then initialize our app and API. after , We created a program , And we are sending a GET request , Explain that if someone clicks on this program , Then he will get Hello world As JSON Response in format . To open a specific URL, We use add resource Method and route it to the default slash . To run this file , have access to POSTMAN Tools ( A kind of API Maintenance tools ) To create 、 Testing and management API. You can also use requests The request module tests this with the following code API. First , Run the file above , It will give you localhost URL, Then at another command prompt , Run the following code file :

import requests
url = "http://127.0.0.1:5000/"
response = requests.get(url=url)
print(response.text)
{
"Hello": "World"
}

adopt Flask RESTApi understand HTTP request

Through the study of the above content , Compared with you REST API I have a preliminary impression . Next we will continue to explore the use of REST API Different HTTP Method , Where we define a list , The list will be in the form of a dictionary (JSON object ) Store all data obtained from the server in the form of . This is very important , Because we have different in the project api To get data , Not data from other places .

First create a API, Create... In it 3 One is called GET、POST and DELETE Of HTTP Method , And create a custom URL, When requested POST When the method is used , It will take Name As input ; In the request GET When the method is used , Return the name to ; stay DELETE when , If the name exists , We will delete the name , Visiting it again will give us NULL.

Create a file and write the following code :

from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
data = []
class People(Resource):
  def get(self):
  for x in data:
    if x['Data'] == name:
     return x
  return {'Data': None}
 def post(self, name):
   temp = {'Data': name}
   data.append(temp)
   return temp
 def delete(self):
   for ind, x in enumerate(data):
    if x['Data'] == name:
     temp = data.pop(ind)
     return {'Note': 'Deleted'}
api.add_resource(People, '/Name/')
if __name__ == '__main__':
 app.run(debug=True)

open POSTMAN API Tools and click on each HTTP Method request . First , When we use post request Name when , It gave us a name. When getting a request , We will return name. It is deleted when it is deleted , When it is retrieved again , It will give you back NULL.

give the result as follows

How to be in Flask REST API We use decorators in our daily life

We use the API To monitor IP Address 、cookie etc. . We will continue to learn how to use the... With decorators Flask API. Decorator is a function that takes another function as a parameter and returns another function . It can also be understood as without changing or modifying the current function , A feature that provides some additional functionality to existing features .

Here we create a new file , I'll show you by creating two decorators . In the first file , Write an external time function that returns the execution time of the code . We from functools modular ( For higher order python The standard module of the function ) Import applies to wrapper Functional wrap Decorator . It updates the wrapper function by copying all the parameters .

from flask import Flask
from flask_restful import Resource, Api
import datetime
from flask import request
from functools import wraps
app = Flask(__name__)
api = Api(app)
def time(function=None):
  @wraps(function)
   def wrapper(*args, **kwargs):
     s = datetime.datetime.now()
     _ = function(*args, **kwargs)
     e = datetime.datetime.now()
     print("Execution Time : {} ".format(e-s))
     return _
   return wrapper
class HelloWorld(Resource):
  @monitor
   def get(self):
     return {"hello": "world"}
api.add_resource(HelloWorld, "/")
if __name__ == "__main__":
  app.run(debug=True)

We create a second decorator to monitor cookie and IP Address , So create the following function . Not to hello world Function to add a time decorator , Instead, add the monitor decorator and run the code .

def monitor(function=None):
    @wraps(function)
    def wrapper(*args, **kwargs):
        _ = function(*args, **kwargs)
        print("Ip Address  : {} ".format(request.remote_user))
        print("Cookies : {} ".format(request.cookies))
        print(request.user_agent)
        return _
    return wrapper

How to make Flask API More secure

When we design API when , We should also pay attention to safety , Because many people will visit it . because API May contain some confidential data between the parties , So we can specify that only authorized people can access API, So what do we do? ? You can use Flask Basic Authentication . Of course , You need to use pip Command to install this flask modular .

pip install flask-httpauth

We're building a API And define User The data dictionary , It contains the user name and password . When working in real-time use cases , The user name and password can be accepted through the configuration file or from the database . First , We create a main function to match the username and password , And create a GET Method , This method represents any click on this API People who , If you are not logged in , We can't access the data .

from flask import Flask
from flask_restful import Resource, Api
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
api = Api(app, prefix="/api/v1")
auth = HTTPBasicAuth()
USER_DATA = {
 "admin": "SuperSecretPwd"
}
#route to verify the password
@auth.verify_password
def verify(username, password):
 if not(username and password):
   return False
  return USER_DATA.get(username) == password
class PrivateResource(Resource):
 @auth.login_required
 def get(self):
    return {"How's the Josh": "High"}
api.add_resource(PrivateResource, '/private')
if __name__ == '__main__':
  app.run(debug=True)

When we use POSTMAN When running the above file , We will try to get data without logging in , To show you unauthorized access .

Now go to authorization , And click Basic authorization. Enter your username and password , And then click GET Request to get the desired results .

This is protection Flask API Methods , It's also the most basic way , Of course, there are more and more advanced methods , I won't give you too much introduction here .

How to be in Flask API  Enable tracing on

So far we have learned how to protect our API, Access is forbidden during unauthorized login , But if we still want to know where the visitors are ( Latitude and longitude points )、IP Address 、 Server name ( For example, to access API People's details ), We can also continue to configure , Use REST API Basic flask Tracking applications . First , Use PIP Command to install flask Tracking package .

pip install flask-track-usage

Next, take a look at the program :

from flask import Flask, g
app = Flask(__name__)
app.config['TRACK_USAGE_USE_FREEGEOIP'] = False
app.config['TRACK_USAGE_INCLUDE_OR_EXCLUDE_VIEWS'] = 'include'
from flask_track_usage import TrackUsage
from flask_track_usage.storage.printer import PrintWriter
from flask_track_usage.storage.output import OutputWriter
t = TrackUsage(app, [
  PrintWriter(),
  OutputWriter(transform=lambda s: "OUTPUT: " + str(s))
 ])
@t.include
@app.route('/')
def index():
   g.track_var["optional"] = "Write_Something"
   return "Hello"
#Run the application
if __name__ == "__main__":
  app.run(debug=True)

The program imports Track Usage、Input writer and output writer To create a tracking application . take flask app Pass to Track Package and use the output writer , And use lambda Function writes output in string format . After the slash Create a basic route on , And include the trace application as a decorator .g On behalf of the whole , Indicates that the data is global in context . therefore , Create a basic API, It returns... In the browser "Hello", At the same time, get the information of all personnel at the back end .

How to REST API Write unit test code

A good example has been created for the case REST API. For all that , We also need to REST API Write unit test code , Because from API Identify common errors in , It is very important to ensure production safety .

Here is how to create a file named run And develop the following simple API.

from flask import Flask
from flask_restful import Resource, Api
import json
app = Flask(__name__)
api = Api(app)
class Helloworld(Resource):
 def __init__(self):
   pass
 def get(self):
   return json.dumps({"Message": "Fine"})
api.add_resource(Helloworld, '/')
if __name__ == '__main__':
  app.run(debug=True)

Now create another one named test The file of , Write in it for API Code for unit testing . The most common scenario is to perform the following three basic unit tests .

  • Check if the response code is 200

  • Check from API Whether the content written is an application JSON Format

  • Check that all the keys we are accessing exist in API Data processing

from run import app
import unittest
class FlaskTest(unittest.TestCase):
 #Check for response 200
 def test_inde(self):
  tester = app.test_client(self) #tester object
  response = tester.get("/")
   statuscode = response.status_code
   self.assertEqual(statuscode, 200)
 #check if the content return is application JSON
 def test_index_content(self):
  tester = app.test_client(self)
   response = tester.get("/")
   self.assertEqual(response.content_type, "application/json")
 #check the Data returned
 def test_index_data(self):
   tester = app.test_client(self)
  response = tester.get("/")
   self.assertTrue(b'Message' in response.data)
if __name__ == '__main__':
 unittest.main()

If you have learned about web crawlers , You should know 200 Responding means responding to a particular URL The request for has been successfully sent , And return the response .

Okay , That's all of this article . Here we have learned to create from scratch Flask REST API , And maintain it easily and safely .

Flask As Python Web The most famous lightweight in the field Web Development framework , For committed Web For the students of development , Master the basic Flask Skills are still very necessary , Have you learned ?

 Recommended reading :
introduction :  The most complete zero Foundation Python The problem of   |  Zero Basics 8 Months Python  |  Actual project  | learn Python That's the shortcut
dried food : A short comment on crawling Douban , The movie 《 The rest of us 》 | 38 year NBA Best player analysis  |    From people's expectation to public praise ! Tang Dynasty detective 3 disappointing   |  Laugh at the story of the new Yitian dragon slaying  |  Riddle answer King  | use Python Make a massive sketch of my little sister  | Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Interest : Pinball game   |  squared paper for practicing calligraphy   |  Beautiful flowers  |  Two hundred lines Python《 Cool run every day 》 game !
AI:  A robot that can write poetry  |  Color the picture  |  Forecast revenue  |  Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Gadget : Pdf turn Word, Easily handle forms and watermarks ! |  One touch html Save the page as pdf!|   bye PDF Withdrawal charges ! |  use 90 Lines of code create the strongest PDF converter ,word、PPT、excel、markdown、html One click conversion  |  Make a nail low-cost ticket reminder ! |60 Line of code to do a voice wallpaper switcher, look at my little sister every day !|

Annual hot money copy

  • 1). Oh my god !Pdf turn Word use Python Easy to handle !

  • 2). learn Python It's delicious ! I use 100 Line of code to make a website , Help people PS Travel pictures , Earn a chicken leg to eat

  • 3). Premiere billions , Hot all over the net , I analyzed 《 My sister 》, Discovered the secrets  

  • 4).80 Line code ! use Python Make a dorai A Dream separation  

  • 5). What you have to master 20 individual python Code , short , Useful  

  • 6).30 individual Python Strange sexual skills Collection  

  • 7). I summed up 80 page 《 Rookie Science Python Select dry goods .pdf》, Is dry  

  • 8). bye Python! I have to learn Go 了 !2500 Word depth analysis !

  • 9). Found a licking dog welfare ! This Python Reptile artifact is great , Automatically download sister pictures

Click to read the original , see B My station 20 A video !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved