4.4. پاسخها
To respond to a request, we use instances of the Response
class or its subclasses
inside the handler function.
Default Backendpy responses include Text
, HTML
,
JSON
, Binary
, File
,
and Redirect
, but you can also create your own custom response types by extending
the Response
class.
The details of each of the default response classes are as follows:
Example usage:
from backendpy.router import Routes
from backendpy.response import Text
routes = Routes()
@routes.get('/hello-world')
async def hello_world(request):
return Text('Hello World!')
Example usage:
from backendpy.router import Routes
from backendpy.response import JSON
routes = Routes()
@routes.get('/hello-world')
async def hello_world(request):
return JSON({'message': 'Hello World!'})
Example usage:
from backendpy.router import Routes
from backendpy.response import HTML
routes = Routes()
@routes.get('/hello-world')
async def hello_world(request):
return HTML('<html><body>Hello World!</body></html>')
Example usage:
import os
from backendpy.router import Routes
from backendpy.response import File
routes = Routes()
@routes.get('/hello-world')
async def hello_world(request):
return File(os.path.join('images', 'logo.jpg'))
There is another type of response to quickly return a success response in predefined json format, which is as follows:
Example usage:
from backendpy.router import Routes
from backendpy.response import Success
routes = Routes()
@routes.get('/hello-world')
async def hello_world(request):
return Success()
@routes.post('/login')
async def login(request):
return Success('Successful login!')
توجه
The json format used in the Success
response is similar to the
Error
response, and these two types of responses can be used together in a project.
Refer to the خطاهای از پیش تعریف شده section for information on how to use the Error
response.