The advantage of Python developing web services is high development efficiency, which may only require one-fifth of the amount of Java code.
Python has many frameworks for building web services. This article introduces two frameworks, Django and bottle.
First, install the framework
The installation is successful, and the version is 1.11.28. The framework files are installed in the \python27\Scripts directory (just search for Scripts in the Python installation directory on the computer).
First enter the \python27\Scripts directory, and create the project jinanwx (any name starts)
You can see the directory of the newly created project in the same directory
Enter python27\Scripts\jinanwx\jinanwx. Create our own module
The simple code written in jgotest01.py is as follows
The function of the module is to return a json format result.
Then you need to change the urls.py module
The catalog file is as follows
It's that simple, create a new file and modify another file, and it's done.
Return to the previous directory to start the service
Start successfully, try browser access
Development functions are not particularly complex web services, you can consider using the bottle framework, which is lighter than Django. The bottle example is demonstrated under Linux.
Use the bottle frame to install first. One instruction is done.
# pip install bottle
Enter the Python command line import bottle, if no error is reported, it is successful.
My web service is a file bottleweb.py, the code is as follows, some explanations are in the code comments
# coding=utf-8from bottle import(run, route,get, post, put,delete, request, hook, response, static_file, app)import json
import MySQLdb #In this example, you need to operate the database, otherwise you don’t need to write this line. The database package pip is estimated to be unsuccessful. I use yum install MySQL-python successful
import sys
reload(sys)
sys.setdefaultencoding('utf8')import bottle
app = bottle.default_app()#Processing static resources need to be defined, no static resources can not write this line
# The following two are required when building vue scaffolding@Hook content, otherwise it will report cross-domain resource access errors
@ hook('before_request')
def validate():
REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')if REQUEST_METHOD =='OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
request.environ['REQUEST_METHOD']= HTTP_ACCESS_CONTROL_REQUEST_METHOD
@ hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin']='*'
response.headers['Access-Control-Allow-Methods']='GET,POST,PUT,DELETE,OPTIONS'
response.headers['Access-Control-Allow-Headers']='*'
@ route('/test2020/dist/<path>')#The address of the static resource under the web service, the route and app of the front-end static resource are not put.route can not be written
def stat(path):returnstatic_file(path, root='./dist/')
@ app.route('/test2020/dist/static/js/<path>')
def js(path): #I wrote these directories like this because the directory structure after vue is packaged is static in dist, etc.
returnstatic_file(path, root='./dist/static/js/')
@ app.route('/test2020/dist/static/css/<path>')
def css(path):returnstatic_file(path, root='./dist/static/css/')
@ get('/test2020/date')#Return the date in a table, you will understand by looking at SQL
def helloins():
db = MySQLdb.connect("127.0.0.1","yourusername","yourpassword","yourDBname", charset='utf8')
cursor = db.cursor()
sql ="select DISTINCT date from testtable"
print sql
cursor.execute(sql)
data = cursor.fetchall()
jsondata={}
results=[]for row in data:
result ={}
result['DATE']= row[0]
results.append(result)
jsondata['code']=0
jsondata['datas']=results
return jsondata #Return json format in order to facilitate the front-end vue reception and processing, in fact, various types can be returned
@ get('/test2020/helloworld')
def helloworld():return'hello world!'if __name__ =='__main__':run(host='0.0.0.0', port=2020, debug=True, reloader=True)
Execute in the directory where bottleweb.py is located
# python bottleweb.py
The web service is started. Browser visit http://127.0.0.1:2020/test2020/helloworld to see the effect.
If the MySQL database is installed, you can test whether the url of test2020/date can return results
As long as the database has the following data
The front-end page looks like this, for the user to select a certain date.
The front end is developed with vue+vux, and the packaged and printed things are uploaded to the dist static resource directory mentioned in the code.
If you think the above code is a bit complicated, you can delete all route, app.route stuff, delete the /test2020/date statement block, delete @hook, delete MySQL stuff, and ignore the front-end stuff at all. A simple bottle web service is equivalent to hello world.
It is recommended to understand the above code as much as possible, which involves static resources and databases, which are necessary content for web services.
To share a pip problem encountered, my Python version is very low 2.6.6. Originally by installing epel of yum, the useful pip has been successfully installed. But every time I use pip command, the bottom will prompt to upgrade
You are using pip version 9.0.3, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command
I executed pip install --upgrade pip upgrade, and then the pip command cannot be used. And after the upgrade, there is no corresponding installation package when you want to install back to the lower version of pip. Yum can only find the 20.0.2 version (will the old version be overwritten?).
http://bootstrap.pypa.io/2.6/get-pip.py
After downloading get-pip.py, it cannot be installed successfully. Finally, after downloading the installation file of version 2.6 at the above address, the pip that can be used is successfully installed.
Compared with java, python has a small amount of web code and fewer libraries to install. If it can meet the functional and performance requirements, python may be a better choice.
Recommended Posts