作者:如痴如醉as_961 | 来源:互联网 | 2023-09-10 16:36
框架必要的配置importsysfromdjango.conf.urlsimporturlfromdjango.confimportsettingsfromdjango.
框架必要的配置

import sys
from django.conf.urls import url
from django.conf import settings
from django.http import HttpResponse
from django.core.management import execute_from_command_line
# 设置框架配置
settings.configure(
DEBUG= True, # 和flask的debug一样
SECRET_KEY= 'aaa', # 用于加密的字符串
ROOT_URLCOnF=__name__, # 此配置为在当前文件里面找url映射的配置
MIDDLEWARE_CLASSES=(
'django.middleware.commom.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
)
实现访问hello/内容/,返回内容

# 实现访问返回访问请求中的参数
def hello(request, user):
return HttpResponse(user)
# 通过正则匹配url,做视图映射
urlpatterns = (
url( r'^hello/(?P\w+)/$', hello),
url(r'^$', index)
)


django的JsonResponse处理返回信息

from django.http import JsonResponse
def test(request):
print(dir(request))
data = {
'path': request.path,
'method': request.method,
'scheme': request.scheme,
'host': request.get_host(),
'port': request.get_port(),
'COOKIEs': request.COOKIES,
'get': request.GET,
'post': request.POST,
}
return JsonResponse(data)
# 通过正则匹配url,做视图映射
urlpatterns = (
url( r'^test/$', test),
url( r'^hello/(?P\w+)/$', hello),
url(r'^$', index)
)
请求


静态文件
项目结构

实现访问http://127.0.0.1:8888/hello/用户名/,输出html里的某些内容
html

这是测试
我是用户:{{ user }}
{% for h in hobbit %}
爱好是:{{ h }}
{% endfor %}
css

h2 {
background-color: red;
}
主程序,需要加入一些模板的配置



import os
import sys
from django.shortcuts import render
from django.conf.urls import url
from django.conf import settings
from django.core.management import execute_from_command_line
BASE_DIR = os.path.dirname(__file__) # 定义当前工程目录为basedir
# 设置框架配置
settings.configure(
DEBUG=True,
ALLOWED_HOSTS=['*'],
SECRET_KEY='aaa', # 用于加密的字符串
ROOT_URLCOnF=__name__, # 此配置为在当前文件里面找url映射的配置
MIDDLEWARE_CLASSES=(
'django.middleware.commom.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
STATIC_URL='/static/', # 定义静态文件的存放目录,和flask一致
STATICFILES_DIRS=(os.path.join(BASE_DIR, 'static'),), # 静态文件目录,指向BASE_DIR/static(括号里的逗号不能省)
INSTALLED_APPS=('django.contrib.staticfiles',), # Django使用静态文件需要安装即在配置中录入此信息(括号里的逗号不能省)
# 模板的配置
TEMPLATES=[{
# 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Django自带的模板引擎
'BACKEND': 'django.template.backends.jinja2.Jinja2', # Jinja2的模板引擎
'APP_DIRS': True, # APP_DIRS为True则默认app下的templates目录,否则使用下一行DIRS声明的目录
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'OPTIONS': {}}]
)
# 实现访问返回访问请求中的参数
def hello(request, user):
# return HttpResponse(user)
cOntext= {
'user': user,
'hobbit': ['看书', '写代码']
}
return render(request, 'hello.html', context)
# 通过正则匹配url,做视图映射
urlpatterns = (
# url( r'^test/$', test),
url(r'^hello/(?P\w+)/$', hello),
# url(r'^$', index)
)
访问
