大佬教程收集整理的这篇文章主要介绍了测试同学动手搭个简易web开发项目,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
node.Js,vue.Js,axios,python,django,orm,restful API,djangorestframework,MysqL,Nginx,jenkins.
windows 7 旗舰版,service Pack 1。
>node -v
v12.18.0
>npm -v
6.14.4
>vue -V(大写)
@vue/cli 4.4.1
>python --version
Python 3.7.2
>python -m django --version
3.0.7
>MysqLadmin --version
MysqLadmin Ver 8.0.19 for Win64 on x86_64 (MysqL Community Server - GPL)
命令行登录MysqL,
>MysqL -u root -p
Enter password: ******
查询数据库,
@H_485_15@mysqL> show databases; +--------------------+ | Database | +--------------------+ | information_scheR_931_11845@a | | MysqL | | new_scheR_931_11845@a | | perfoRMANce_scheR_931_11845@a | | sakila | | sys | | world | +--------------------+ 7 rows in set (0.00 seC)
在Nginx安装目录执行start Nginx
,浏览器访问http://localhost:80,
安装后,会@R_262_9871@http://localhost:8080/,
软件安装过程就不赘述了,聪明的你一定知道怎么安。
本文的目的是走通整个项目的链路,于是会“弱化”掉系统功能的实现。
执行django-admin startproject djangotest
创建项目。
cd djangotest
,执行python manage.py startapp myapp
创建应用。
python manage.py runserver
,启动服务,访问http://localhost:8000/,
安装MysqLclIEnt和djangorestframework,
pip --default-timeout=6000 install -i https://pypi.tuna.tsinghua.edu.cn/simple MysqLclIEnt
pip --default-timeout=6000 install -i https://pypi.tuna.tsinghua.edu.cn/simple djangorestframework
在setTings.py中,添加'rest_framework'和'myapp',
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.ContentTypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','myapp',]
同时修改数据库配置,
DATABASES = {
'default': {
'ENGINE': 'django.db.BACkends.MysqL','HOST': '127.0.0.1','PORT': 3306,'name': 'world','USER': 'root','passworD': '123456'
}
}
在myapp\models.py添加model,model叫做HellloDjango,有2个字段ID和name,
from django.db import models
# Create your models here.
class HelloDjango(models.Model):
ID = models.autoFIEld(priMary_key=TruE)
name = models.CharFIEld(null=false,max_length=64,unique=TruE)
执行python manage.py makemigrations
,提交,
>python manage.py makemigrations
Migrations for 'myapp':
myapp\migrations\0001_initial.py
- Create model HelloDjango
执行python manage.py migrate
,创建,
>python manage.py migrate
Operations to perform:
Apply all migrations: admin,auth,ContentTypes,myapp,sessions
Running migrations:
Applying ContentTypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying ContentTypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_ContentTypes_0002... OK
Applying auth.0007_alter_valIDators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying myapp.0001_initial... OK
Applying sessions.0001_initial... OK
看看数据库,新增了auth_和django_开头的表,以及model映射的表myapp_Hellodjango,
@H_485_15@mysqL> show tables; +----------------------------+ | tables_in_world | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | city | | country | | countrylanguage | | django_admin_log | | django_content_type | | django_migrations | | django_session | | myapp_Hellodjango | +----------------------------+ 14 rows in set (0.00 seC)
插入2条测试数据,
@H_485_15@mysqL> insert into myapp_Hellodjango(Name) values('Hello'); query OK,1 row affected (0.09 seC) MysqL> insert into myapp_Hellodjango(Name) values('django'); query OK,1 row affected (0.20 seC) MysqL> SELEct * from myapp_Hellodjango; +----+--------+ | ID | name | +----+--------+ | 2 | django | | 1 | Hello | +----+--------+ 2 rows in set (0.00 seC)
照着官网的例子,在myapp目录下新增urls.py,添加rest代码,
from django.conf.urls import url,include
from rest_framework import routers,serializers,vIEwsets
from .models import HelloDjango
# serializers define the API representation.
class Helloserializer(serializers.HyperlinkedModelserializer):
class Meta:
model = HelloDjango
fIElds = ['ID','name']
# VIEwSets define the vIEw behavior.
class HellovIEwSet(vIEwsets.ModelVIEwSet):
queryset = HelloDjango.objects.all()
serializer_class = Helloserializer
# Routers provIDe an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'Hello',HellovIEwSet)
urlpatterns = [
url(r'demo/',include(router.urls)),]
在djangotest下的urls.py中添加路由,
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/',admin.site.urls),path('API/',include('myapp.urls'))
]
通过这2个urls.py文件的指定,API接口的路径为,/API/demo/Hello。
执行python manage.py runserver
启动服务,使用postman来调用http://127.0.0.1:8000/API/demo/Hello/。先发1个post请求,往数据库新增1条数据,
再发1个get请求,会看到返回了3条数据,2条预先插入的数据,1条post请求新增的数据,
在djangotest根目录下,执行vue create vuetest
,创建vue工程。
默认安装,一路回车,啪啪啪。
开始创建,
Vue Cli v4.4.1
a CreaTing project in D:\cicd\vuetest.
a Initializing git repository...
aa Installing Cli plugins. This might take a while...
创建成功,
a successfully created project vuetest.
a Get started with the following commands:
$ cd vuetest
$ npm run serve
执行cd vuetest
和npm run serve
,前端工程就启动起来了,访问http://localhost:8080/,Welcome to Your Vue.Js App,
此时djangotest的目录结构为,
├─djangotest
│ ├─djangotest
│ ├─myapp # app
│ ├─vuetest # 前端
│ ├─manage.py
修改vuetest\src\components\HelloWorld.vue,添加{{info}}
,用来展示后端API返回的数据,
<div class="Hello">
{{info}}
<h1>{{ msg }}</h1>
同时在<script>
中使用axios添加AJAX请求,请求http://127.0.0.1:8000/API/demo/Hello/,将response.data赋值给info,
<script>
export default {
name: 'HelloWorld',props: {
msg: String
},data() {
return {
info: 123
}
},mounted () {
this.$axios
.get('http://127.0.0.1:8000/API/demo/Hello/')
.then(response => (this.info = response.data))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}
</script>
为了运行起来,需要安装axios,
npm install --save axios
并在vuetest\src\main.Js中引入,
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$axios = axios;
new Vue({
render: h => h(App)
}).$mount('#app')
分别启动后端和前端服务,
python manage.py runserver
cd vuetest
npm run serve
嚯!AJAX请求失败了,F12可以看到报错信息,
localhost/:1 Access to XMLhttprequest at 'http://127.0.0.1:8000/api/demo/Hello/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
django的端口是8000,vue的端口是8080,vue在请求django的时候,出现了跨域问题。浏览器有个同源策略,域名+端口+协议都相同才认为是同一来源。
通过配置django来解决,先安装django-cors-headers,
pip install django-cors-headers
@H_976_130@mIDDLEWARE = [ 'django.mIDdleware.security.SecuritymIDdleware','django.contrib.sessions.mIDdleware.SessionMIDdleware','corsheaders.mIDdleware.CorsMIDdleware',# 添加 'django.mIDdleware.common.CommonMIDdleware','django.mIDdleware.csrf.CsrfVIEwMIDdleware','django.contrib.auth.mIDdleware.AuthenticationMIDdleware','django.contrib.messages.mIDdleware.messageMIDdleware','django.mIDdleware.clickjacking.XFrameOptionsMIDdleware',] CORS_ORIGIN_ALLOW_ALL = True # 添加
此时vue就可以请求到django提供的接口了,http://localhost:8080/
@H_859_301@前后端结合在vuetest
目录下创建vue.config.Js
,这是因为django只能识别static目录下的静态文件,这里指定vue生成静态文件时套一层static目录,
@H_456_273@module.exports = { assetsDir: 'static' };
在vuetest目录下执行npm run build
,生成静态文件到vuetest/dist文件夹。
修改urls.py,指定django的模板视图,
from django.conf.urls import url
from django.contrib import admin
from django.urls import path,include
from django.vIEws.generic import TemplateVIEw
urlpatterns = [
path('admin/',include('myapp.urls')),url(r'^$',TemplateVIEw.as_vIEw(template_name="index.HTML")),]
TEMPLATES = [
{
'BACKEND': 'django.template.BACkends.django.DjangoTemplates','Dirs': ['vuetest/dist'],'APP_Dirs': True,'OPTIONS': {
'context_processors': [
'django.template.context_processors.deBUG','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},]
指定静态文件目录为vuetest/dist/static,
# Add for vueJs
STATICfileS_Dirs = [
os.path.join(BASE_DIR,"vuetest/dist/static"),]
浏览器访问http://localhost:8000/,显示的不再是django的欢迎页面,而是vue的页面。
前后端结合完成。vue的8080可以停了。
Nginx常用3个命令,启动,重新加载,停止,
Nginx start
Nginx -s reload
Nginx -s stop
修改\conf\Nginx.conf,监听端口改为8090,添加转发proxy_pass http://localhost:8000;
server {
Listen 8090;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
LOCATIOn / {
root HTML;
index index.HTML index.htm;
proxy_pass http://localhost:8000;
}
执行Nginx start
,浏览器访问http://localhost:8090/,也能正常访问djangotest。
通过Nginx将8090转发到了8000。
本来想弄个pipline的,无奈家里这台破机器安装失败,windows也没有linux对jenkins支持好,只能将就做个鸡肋版本。
New Item,命名为vuetest,添加vue的build脚本,
d:
cd D:\cicd\djangotest\vuetest
npm run build
New Item,命名为djangotest,添加django的build脚本,
d:
cd D:\cicd\djangotest
python manage.py runserver
直接执行会报错python不是可运行命令。添加python环境变量,在首页左下角,
@H_616_415@
把路径D:\@R_404_4729@7添加为环境变量path并保存,
@H_555_403@
建好的这2个job就可以用来编译vue和启动django了,
以上是大佬教程为你收集整理的测试同学动手搭个简易web开发项目全部内容,希望文章能够帮你解决测试同学动手搭个简易web开发项目所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。