Like its portability, the use of the Bottle library is also very simple. I believe that before reading this article, readers already have a simple understanding of python. So what kind of mysterious operation can complete the functions of a server with hundreds of lines of code? let us wait and see.
1. Bottle library installation
1) Use pip to install
2) Download the Bottle file
https://github.com/bottlepy/bottle/blob/master/bottle.py
2. "HelloWorld!"
The so-called success of everything Let’s start with Hello World and learn about the basic mechanism of Bottle from this simple example.
First the code:
First we import the get and run methods from the bottle library.
Next, we have to build a website. We must first have an IP address and a port. This part of the function is completed by run. In the test phase, we use 127.0.0.1 (this machine address) and port 80 (browser default port):
Run this code python HelloWorld.py
like this The website server is now running. Open the browser and enter 127.0.0.1(:80)
. The familiar 404 error message is Not found: '/' . This is of course, because in addition to the server, the website also has a very important component - the web page!
When the browser accesses the IP address, it sends a get request to the IP and waits for the web page data to be returned. Then our bottle library encapsulates the get method to implement this process.
The code is as follows:
#I don’t know if you know the @ symbol above def. This symbol is a decorator in python syntax. The meaning can be simply understood as using the get function to modify the homepage. Here, @get(‘/’) decorates the homepage into the corresponding function when the browser sends the request GET 127.0.0.1/. You can do any processing, and finally return the response to the get request. Here the simple HelloWorld page is returned. If you run it again, you will have this effect:
You can also use the template method encapsulated in bottle to separate the web page data. Written in a .tpl file, the example is as follows:
The run function also has a parameter reloader. Setting it to True will turn on automatic reloading of the web server. The server will be automatically reloaded when you make any changes, enabling hot updates of the website.
3. Dynamic routing and file download
The get('/') we used above is essentially a static routing, and the address is determined before the server runs. Routing can be done this way.
So what if it is a server runtime? For example, accessing files on the website server cannot be done in a static way. In this case, we can use dynamic routing.
Bottle's dynamic routing is implemented by the route method. Similar to get, it also uses decorators to decorate functions to implement routing functions.
#Here we see something unique appearing in the parameters of the decorator: 'name'. The parameters of the modified function have the same name as the parameter after the colon. In the function, you can use the name parameter as a processing variable, and finally return the response.
# Dynamic routing can provide convenience for file routing. There may be hundreds or thousands of files stored in a server, and it is impossible to rely on static addresses for each one.
Here we can see a new function static_file, the first parameter is the file name, the second parameter is the root directory address (that is, the location of the file), the current file The system is:
--HelloWorld.py
--store1.txt
Access the browser to get
Of course you can also put the file in a folder, just replace the root parameter with the address of the folder.
4. POST response and file upload
If we want to implement more complex functions, we not only need to use the GET method, but also the POST method. Here we use Form in HTML language to demonstrate the Bottle library's response to POST requests.
#First we implement a window for uploading files, as above.
The page here is a simple form submission interface. I will not introduce it in detail here. The page you open is as follows:
The following POST response code is as follows:
Import the post method and request from the Bottle library.
Similar to the get method, use post to decorate the response function, and then use request in the function body to obtain the post request body received by the website server. The request.forms.get() method can take out the string corresponding to the Key in the form, the request.files.get() method can take out the file corresponding to the Key in the form, and the save method can be used to store the data to achieve file uploading.
Next we conduct a test:
After clicking upload, we open the server root directory (which is the location of the python file) , check and find that the file has been uploaded successfully!
5. Summary
After completing these functions, you must want to deploy bottle to the network. After all, if it only runs locally, the website will What does it do?
Tsinghuanet provides a public IP for each of our network access points. Use ipconfig in cmd to check the IP address, change the running parameters in run to your public IP, and then Enter the IP address and port number (default 80) in the browser of any device (mobile phones are recommended, computer browsers are sometimes very slow), and you can access it!
The Bottle library also has many powerful functions, including reading and writing cookies, installing, uninstalling and disabling plug-ins. Bottle can also be deployed to other servers, making it very simple to implement multi-threading. , these functions are waiting to be explored by readers!
The above is the detailed content of Python lightweight web framework: Bottle library!. For more information, please follow other related articles on the PHP Chinese website!

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
