-
Notifications
You must be signed in to change notification settings - Fork 1
Quickstart
Create a minimal application is very simple! Look at the following example:
import swapy
@swapy.on()
def root():
return 'Hello swapy!'
if __name__ == '__main__':
swapy.run()
import swapy
imports the swapy module.
@on()
registers the function as a route. @on()
is the same as @on('/')
.
return 'Hello World!'
returns the string Hello World
as response with Content-Type: text/plain
header.
run()
runs the test server. You can use debug=True
for the debug and hot reload mode. Also host='0.0.0.0'
and port=80
are possible arguments.
You can create multiple functions with the same name. It doesn't matter how the name is.
...
@swapy.on(methods=['GET'])
def root():
return 'Hello swapy!'
@swapy.on(methods=['POST'])
def root():
return 'Created swapy!'
@swapy.on(methods=['DELETE'])
def root():
return 'Removed swapy!'
...
This is ugly! There are two other ways to do it. I prefer the last one but the next one is shorter :)
The next example shows that the function root gets the parameter reg
. It is the parameter for the request object. You can use it but you don't have to as you see in other examples.
...
@swapy.on()
def root(req):
if req.method == 'GET':
return 'Hello swapy!'
if req.method == 'POST':
return 'Created swapy!'
if req.method == 'DELETE':
return 'Removed swapy!'
...
...
@swapy.on_get()
def root():
return 'Hello swapy!'
@swapy.on_post()
def root():
return 'Created swapy!'
@swapy.on_delete()
def root():
return 'Removed swapy!'
...
The difference between the first and the last example is that @on()
can route multiple HTTP methods (as default it routes all methods) compared to @on_get()
. @on_get()
can only route one HTTP method.
Another nice feature is that you can add multiple routes to one function. Look at the next example!
...
@swapy.on()
@swapy.on('/home')
def index():
return 'Welcome to swapy!'
...
You can create multiple files like this. An example of a project structure:
myproject/
- app.py
- authentication.py
Now you want to include the authentication
module into the app
module.
import swapy
import authentication
swapy.include(authentication)
...
What does it do?
It merges the route rules from authentication
into app
.
If you want to set a prefix for the authentication
module in app
just use:
...
swapy.include(authentication, prefix='auth')
...
Pretty easy! ❤️