In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to use Flask to build a simple RESTful service. I think it is very practical, so I share it with you. I hope you can get something after reading this article.
One of our current projects is built using Django, which is also based on the consideration of technology expansion. I still hold a conservative attitude towards some large and complete components in Django, so although the project uses Django, it uses as little or no use as possible for many components, so it is difficult to use as much as possible, but now, due to the low dependency, I can match many other solutions.
Of course, for me, I particularly like Django's ORM scheme, which I compared to the lower Flask direction of the ORM scheme SQLAlchemy,Django feels better.
In the direction of RESTful, Django's own third-party implementation of rest_framework is also good, and now it looks like a very simple concept and implementation, which takes a long time to fully understand.
On the other hand, if we take a look at Flask's RESTful scheme, it can also be used for reference.
Flask is much more concise than Django. Let's look at the simplest example of Flask, such as starting a web service and printing out hello world.
The code is as follows:
From flask import Flask
App = Flask (_ _ name__)
@ app.route ('/')
Def hello_world ():
Return 'Hello Worldwide'
If _ _ name__ = ='_ _ main__':
App.run ('192.168.56.102')
The last IP is my server IP, which can be replaced as needed.
Use the following way to run, the service can be turned on.
[root@dev01 flask] # python hello.py
* Running on http://192.168.56.102:5000/ (Press CTRL+C to quit)
192.168.56.1-[19/May/2018 22:29:22] "GET / HTTP/1.1" 200-
192.168.56.1-[19/May/2018 22:29:22] "GET / favicon.ico HTTP/1.1" 404-
192.168.56.1-[19/May/2018 22:29:22] "GET / favicon.ico HTTP/1.1" 404-
The results are as follows:
Please enter a description
Here, if you have done Python Web development students are likely to say, this is not a lie to me, Python's own technology can also be implemented, Python itself has implemented a SimpleHttpServer, you can see a previous article:? How to understand Python web development technology?
The code inside looks more concise:
#! / usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef RunServer (environ, start_response): start_response ('200OK', [(' Content-Type', 'text/html')]) return' Hello, wsgifted Hello if _ _ name__ ='_ main__': httpd = make_server (', 8000, RunServer) print "Serving HTTP on port 8000..." Httpd.serve_forever ()
Let's take a look at a relatively complete example of Flask code, which is referred to: https://www.jianshu.com/p/6ac1cab17929
The code is as follows:
#! / usr/bin/env python
#-*-coding: utf-8-*-
# by vellhe 2017-7-9
From flask import Flask, abort, request, jsonify
App = Flask (_ _ name__)
# temporary storage of test data
Tasks = []
@ app.route ('/ add_task/', methods= ['POST'])
Def add_task ():
# you need to maintain the list structure yourself
If not request.json or 'id' not in request.json or' info' not in request.json:
Abort (400)
Task = {
'id': request.json ['id']
'info': request.json ['info']
}
Tasks.append (task)
Return jsonify ({'result':' success'})
@ app.route ('/ get_task/', methods= ['GET'])
Def get_task ():
If not request.args or 'id' not in request.args:
# if no id is specified, return all
Return jsonify (tasks)
Else:
Task_id = request.args ['id']
Task = filter (lambda t: t ['id'] = = int (task_id), tasks)
Return jsonify (task) if task else jsonify ({'result':' not found'})
If _ name__ = = "_ _ main__":
# if host is set to 192.168.56.102, public network users can also access this service
App.run (host= "192.168.56.102", port=8383, debug=True)
One of the difficulties of this program is how to simulate the POST request in the browser. Of course, you can do it using postman, which can be downloaded on the windows side by referring to this link:
Https://app.getpostman.com/app/download/win64
The second difficulty is to deal with JSON, there are still a lot of references. Although the overall feeling is achievable, all the details need to be controlled by yourself, such as input structure, output structure, matching of information lookup, and mapping of url and methods. Always feel a little muddy, the drag is too heavy, you can you up feeling.
In the way of using RESTful, this module can be introduced into Flask, which is relatively simple and lightweight.
To install flask_restful, you can use one command.
Pip install flask_restful
For example, I have a requirement, to do a basic task management requirements, can be divided into two types of functions, task management and task list management, task management, including viewing tasks, adding, deleting tasks, are corresponding to a single task. The task list is the query and addition of multiple task information.
This requirement, in fact, the basic processing unit is the task, each level can be constantly refined. As far as possible for the application level is more transparent, for example, I will open a url: todos to complete the management of the task list, you can view the task list, add task information.
Todos/todo1 manages a single task, such as adding changes and deleting.
This example may not sound very clear. Let me cite an example in life. For example, when you go to an amusement park, there is only one service desk, where you can recharge, refund and apply for a card. At this point, the requirements may be as follows:
For example, if you give him 100 yuan, it means you have to apply for a card and recharge the corresponding amount (maybe deducting the cost).
For example, if you give him 100 yuan and bring a card, that means you have to recharge.
For example, if you give him a card, it means you need a refund.
So for the above requirements, the input may be simple, but the corresponding business scenario may be completely different. So the above code to achieve this requirement, the logic is still relatively complex, and not clear enough.
One of the advantages of RESTful is that different requirements interfaces can be built based on class. Url, which is open to the public, may be a unified entrance, but it can be refined on this basis. Such as url: / todos and / todos/todo1
Write a program script to implement:
#! / usr/bin/env python
#-*-coding: utf-8-*-
From flask import Flask
From flask_restful import reqparse, abort, Api, Resource
App = Flask (_ _ name__)
Api = Api (app)
TODOS = {
'todo1': {'task':' test1'}
'todo2': {'task':' test2'}
'todo3': {'task':' test3'}
}
Def abort_if_todo_doesnt_exist (todo_id):
If todo_id not in TODOS:
Abort, message= "Todo {} doesn't exist" .format (todo_id))
Parser = reqparse.RequestParser ()
Parser.add_argument ('task')
# Todo
# shows a single todo item and lets you delete a todo item
Class Todo (Resource):
Def get (self, todo_id):
Abort_if_todo_doesnt_exist (todo_id)
Return TODOS[todo _ id]
Def delete (self, todo_id):
Abort_if_todo_doesnt_exist (todo_id)
Del TODOS[todo _ id]
Return', 204
Def put (self, todo_id):
Args = parser.parse_args ()
Task = {'task': args [' task']}
TODOS [todo _ id] = task
Return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
Class TodoList (Resource):
Def get (self):
Return TODOS
Def post (self):
Args = parser.parse_args ()
Todo_id = int (max (TODOS.keys ()) .lstrip ('todo')) + 1
Todo_id = 'todo%i'% todo_id
TODOS [todo _ id] = {'task': args [' task']}
Return TODOS[todo _ id], 201
# #
# # Actually setup the Api resource routing here
# #
Api.add_resource (TodoList,'/ todos')
Api.add_resource (Todo,'/ todos/')
If _ _ name__ = ='_ _ main__':
App.run ('192.168.56.102 recording and debugging True)
The invocation is as follows:
Please enter a description
If you are viewing the information of a task, you can enter it directly to match.
Please enter a description
Take a look at the code, you will find that there are two API registered here, the difference between here and the above program is that it uses Resource to do encapsulation, if I want to add a logic, it is actually very convenient. You don't need to pile up a lot of if-else.
The above is how to use Flask to build simple RESTful services, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.