Today, when developing systems using the VUE framework, you need to use the back-end interface, but the interface has not been developed. I wanted to build a simple API service in the simplest way possible. Since I prefer the Django framework, I wondered if I could build a simple single-file Web service like Flask using the Django framework. Sure enough, I found the excerpt to share with you.
# app.py
import os
import sys
from dataclasses import dataclass
from django.conf import settings
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import path
from django.utils.crypto import get_random_string
Django configuration files, which are equivalent to settings.py configuration files, can be added and removed directly from here
The following are the simplest parameters required to start Django
settings.configure(
DEBUG=(os.environ.get("DEBUG"."") = ="1"),
ALLOWED_HOSTS=["*"].# Disable host header validation
ROOT_URLCONF=__name__, # Make this module the urlconf
SECRET_KEY=get_random_string(
50
), # We aren't using any security features but Django requires this setting
MIDDLEWARE=["django.middleware.common.CommonMiddleware"],)# Modeled the Model using the Dataclass decorator.
@dataclass
class Character:
name: str
age: int
def as_dict(self, id_) :
return {
"id": id_,
"name": self.name,
"age": self.age,
}
You can use the fields directly to construct the data to be returned
characters = {
1: Character("Rick Sanchez".70),
2: Character("Morty Smith".14),}# Django View section, use function Base View directly for convenience
def index(request) :
return HttpResponseRedirect("/characters/")
def characters_list(request) :
return JsonResponse(
{"data": [character.as_dict(id_) for id_, character in characters.items()]}
)
def characters_detail(request, character_id) :
try:
character = characters[character_id]
except KeyError:
return JsonResponse(
status=404,
data={"error": f"Character with id {character_id! r} does not exist."},)return JsonResponse({"data": character.as_dict(character_id)})
# Django Route section, same as url.py
urlpatterns = [
path("", index),
path("characters/", characters_list),
path("characters/<int:character_id>/", characters_detail),
]
Application can be launched using software using the WSGI protocol such as UWSGi.
app = get_wsgi_application()
if __name__ == "__main__":
# introduce a command line startup function for directly launching tests, same as manage.py
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Copy the code
Run the following command to start the service:
python app.py runserver
Copy the code
You can also start using an application such as UWSGi. Use Gunicorn as follows:
gunicorn app:app
Copy the code
Hope can help you ~
More information on how to test and build Django single files can be found on the blog of Adam Johnson, a member of the Django Technical Committee and organizer of Django MeetUp UK.