前后端分离——博客项目
1 初始化 django 博客项目步骤:
创建新虚拟环境, 安装各种包:
$ mkvirtualenv xinjian$ cd xinjian/$ pip install django==1.11.8$ python steup.py install$ pip install PyJWT.whl$ django-admin startproject blog_server
2 更改settings.py 设置:
ALLOWED_HOSTS = [‘*‘] MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware‘, ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘corsheaders.middleware.CorsMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, 将csrf禁用掉 #‘django.middleware.csrf.CsrfViewMiddleware‘, LANGUAGE_CODE = ‘zh-Hans‘ TIME_ZONE = ‘Asia/Shanghai‘
3 创建数据库:
$ mysql -u root -p创建数据库:create database blog_server default charset utf8 collate utf8_general_ci;
4 更改settings.py数据库设置:
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘blog_server‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘123456‘, ‘HOST‘: ‘127.0.0.1‘, ‘PORT‘: ‘3306‘ } }
5 更改settings.py设置
1,INSTALLED_APPS 中添加 corsheaders 2,MIDDLEWARE 中添加 corsheaders.middleware.CorsMiddleware 位置尽量靠前,官方建议 ‘django.middleware.common.CommonMiddleware’ 上方 3,CORS_ORIGIN_ALLOW_ALL= True 布尔值 如果为True 白名单不启用,写在文件的最后面 4,CORS_ORIGIN_WHITELIST =[ #指定白名单,一般不用写 "https://example.com" ] 5, CORS_ALLOW_METHODS = ( ‘DELETE‘, ‘GET‘, ‘OPTIONS‘, ‘PATCH‘, ‘POST‘, ‘PUT‘, ) 6, CORS_ALLOW_HEADERS = ( ‘accept-encoding‘, ‘authorization‘, ‘content-type‘, ‘dnt‘, ‘origin‘, ‘user-agent‘, ‘x-csrftoken‘, ‘x-requested-with‘, ) 7, CORS_PREFLIGHT_MAX_AGE 默认 86400s 8, CORS_EXPOSE_HEADERS [] 扩展头 9, CORS_ALLOW_CREDENTIALS 布尔值, 默认False import os ALLOWED_HOSTS = [‘*‘] # Application definition INSTALLED_APPS = [ ‘corsheaders‘, ‘user‘ ] MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware‘, ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘corsheaders.middleware.CorsMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, #‘django.middleware.csrf.CsrfViewMiddleware‘, ] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘blog_server‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘123456‘, ‘HOST‘: ‘127.0.0.1‘, ‘PORT‘: ‘3306‘ } } LANGUAGE_CODE = ‘zh-Hans‘ TIME_ZONE = ‘Asia/Shanghai‘ USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = ‘/static/‘ CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( ‘DELETE‘, ‘GET‘, ‘OPTIONS‘, ‘PATCH‘, ‘POST‘, ‘PUT‘, ) CORS_ALLOW_HEADERS = ( ‘accept-encoding‘, ‘authorization‘, ‘content-type‘, ‘dnt‘, ‘origin‘, ‘user-agent‘, ‘x-csrftoken‘, ‘x-requested-with‘, ) #关掉路由自动补全 APPEND_SLASH = False
6 blog_server/urls.py: from django.conf.urls import url, include
from django.contrib import admin from . import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^test_api‘, views.test_api), #添加user模块 url映射 url(r‘v1/users‘, include(‘user.urls‘)), #添加btoken模块 url映射, 该模块用登录操作 url(r‘v1/token‘, include(‘btoken.urls‘)) ]
7 新建blog_server/views.py:
from django.http import JsonResponse def test_api(request): #JsonResponse 1,将返回内容序列化成json #2,response中添加 content-type: application/json return JsonResponse({‘code‘:200})
8 在虚拟环境安装flask
pip install flask
9 创建文件包 client, 并创建 flask_client.py文件
iew Code
10 创建client/static/的css, js, images 包, 并创建各种文件
11 创建模板:
<!DOCTYPE html> <html> <!-- author:guojunyu date:2019-05 desc:this demo is about blog. PLEASE NOTE:If you have trouble running it ,try any of the other demos or connect with auther. A ny individuals and organizations and not for commercial use, professiona website for customized web site. --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/css/login_reglogin.css"/> <script src="/static/js/jquery.min.js" type="text/javascript"></script> <title>登陆</title> </head> <body> <div class="bg"> <img src="/static/images/b.jpg" alt=""> </div> <div class="main"> <div class="header" > <h1>Login!</h1> </div> <p></p> <ul class="right-form"> <h2>Login:</h2> <li><input type="text" class="username" name="username" placeholder="Username" required/></li> <li><input type="password" class="password" name="password" placeholder="Password" required/></li> <input type="button" value="登录" onclick="login()"> <div class="clear"> </div> </ul> <div class="clear"> </div> </div> </body> <script> function login(){ var username = $(‘.username‘).val() var password = $(‘.password‘).val() var post_data = {‘username‘:username, ‘password‘:password } $.ajax({ // 请求方式 type:"post", // contentType contentType:"application/json", // dataType dataType:"json", // url url:"http://127.0.0.1:8000/v1/tokens", // 把JS的对象或数组序列化一个json 字符串 data:JSON.stringify(post_data), // result 为请求的返回结果对象 success:function (result) { if (200 == result.code){ window.localStorage.setItem(‘dnblog_token‘, result.data.token) window.localStorage.setItem(‘dnblog_user‘, result.username) alert(‘登陆成功‘) refer_url = document.referrer //如果是项目内部的请求,回跳到上一步 if (refer_url.search(‘127.0.0.1‘) != -1){ window.location = refer_url; }else{ window.location = ‘/‘ + result.username + ‘/topics‘; } }else{ alert(result.error) } } }); } </script> </html>
相关推荐
jxiao000 2020-09-29
zjutzmh 2020-09-25
ApeLife技术 2020-07-04
ApeLife技术 2020-06-26
Ken专注后端技术 2020-05-28
nullcy 2020-05-26
SAMXIE 2020-05-12
hzyuhz 2020-05-04
林大夏 2020-03-27
jxiao000 2020-02-20
bowean 2020-02-19
shuiluobu 2020-01-29
Ken专注后端技术 2020-01-29
ChinaGuanq 2020-01-19
xxuncle 2020-01-17
Julywhj 2019-12-27
ApeLife技术 2019-12-22