测试同学动手搭个简易web开发项目(代码片段)

自动化代码美学 自动化代码美学     2022-12-26     160

关键词:

技术栈

node.js, vue.js, axios, python, django, orm, restful api, djangorestframework, mysql, nginx, jenkins.

环境配置

操作系统

Windows 7 旗舰版,Service Pack 1。

前端

Node.js

>node -v
v12.18.0
>npm -v
6.14.4

Vue.js

>vue -V(大写)
@vue/cli 4.4.1

后端

Python

>python --version
Python 3.7.2

Django

>python -m django --version
3.0.7

数据库

MySQL

>mysqladmin --version
mysqladmin  Ver 8.0.19 for Win64 on x86_64 (MySQL Community Server - GPL)

命令行登录mysql,

>mysql -u root -p
Enter password: ******

查询数据库,

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| new_schema         |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

代理

Nginx

在nginx安装目录执行start nginx,浏览器访问http://localhost:80,

1592456182850

持续集成

Jenkins

安装后,会自动打开http://localhost:8080/,

1592979912495_副本

软件安装过程就不赘述了,聪明的你一定知道怎么安。

项目搭建

本文的目的是走通整个项目的链路,于是会“弱化”掉系统功能的实现。

创建后端工程

执行django-admin startproject djangotest创建项目。

cd djangotest,执行python manage.py startapp myapp创建应用。

python manage.py runserver,启动服务,访问http://localhost:8000/,

1591519905326_副本

创建RESTful API

安装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,

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条测试数据,

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条数据,

1592902408582_副本

再发1个get请求,会看到返回了3条数据,2条预先插入的数据,1条post请求新增的数据,

1592902449583_副本

创建前端工程

在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 vuetestnpm run serve,前端工程就启动起来了,访问http://localhost:8080/,Welcome to Your Vue.js App,

1591501593139_副本

前端调后端接口

此时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

在settings.py中添加中间件和开关,

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/

1592972876066_副本

前后端结合

vuetest目录下创建vue.config.js,这是因为django只能识别static目录下的静态文件,这里指定vue生成静态文件时套一层static目录,

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/\', admin.site.urls),
    path(\'api/\', include(\'myapp.urls\')),
    url(r\'^$\', TemplateView.as_view(template_name="index.html")),
]

在settings.py中配置模板目录为dist文件夹,

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可以停了。

1592972876066_副本

Nginx转发

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

1592991544913_副本

New Item,命名为djangotest,添加django的build脚本,

d:
cd D:\\cicd\\djangotest
python manage.py runserver

1592991578357_副本

直接执行会报错python不是可运行命令。添加python环境变量,在首页左下角,

1592983220698_副本

把路径D:\\Python37添加为环境变量path并保存,

1592983242033_副本

建好的这2个job就可以用来编译vue和启动django了,

1592991709156_副本


版权申明:本文为博主原创文章,转载请保留原文链接及作者。

c#用winform开发一个简易双色球项目(代码片段)

开始画面抽奖中: 抽奖结果: 需要一个随机数Random的帮助类,让随机数唯一性publicclassRandomHelperpublicintGetNum(intmin,intmax)Thread.Sleep(1000);//随机休息1秒returnGetIntNum(min,max);///<summary>///获取随机数,解决重复问题///</s 查看详情

项目的环境分析建议

...定程度,各位同学会合并代码,进行联调。 Test 测试环境 也就是我们测试同学干活的环境啦,在此环境进行测试。 PreProduction 预生产 查看详情

web开发python实现web服务器(flask测试统计图表)(代码片段)

...Werkzeug,模板引擎则使用Jinja2。Flask使用BSD授权。4、Flask测试网页(统计图表)4.1基于echarts的统计图的网页https://echarts.a 查看详情

springmvc底层机制的简易实现(代码片段)

SpringMVC底层机制的简易实现项目基础配置xml文件开发指南开发步骤1.初始化数据2.中央控制器-分发请求3.开发者角度4.视图解析器开发总结项目基础<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifa... 查看详情

web开发python实现web服务器(flask测试后台框架模板)(代码片段)

1、前言提示:Flask是一个用python语言基于Werkzeug工具箱编写的轻量级web开发框架,它主要面向需求简单,项目周期短的小应用。Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容... 查看详情

前端vue+后端django项目创建以及自动部署流程(代码片段)

...发的同学先写完代码,然后交付给运维的同学部署到测试和生产环境。DevOps可以让整个流程自动化,开发的同学只需要稍微会一些工具就可以完成部署的工作。前端Vue项目创建+自动部署准备工作:本地安装了Node、... 查看详情

前端vue+后端django项目创建以及自动部署流程(代码片段)

...发的同学先写完代码,然后交付给运维的同学部署到测试和生产环境。DevOps可以让整个流程自动化,开发的同学只需要稍微会一些工具就可以完成部署的工作。前端Vue项目创建+自动部署准备工作:本地安装了Node、... 查看详情

项目环境稳定性指标建设之路(代码片段)

引言项目环境是集团研发同学联调测试必不可少的平台型工具之一,其环境申请与释放动态灵活,环境间流量相互隔离,在开发和上线前的个人自测以及全链路联调场景下有着不可替代的重要作用。一个稳定易用的项... 查看详情

如何测试客户端web页面性能(代码片段)

...a;白屏时间首屏时间加载成功率2020年的春节活动采用手工测试,主要采用录屏分帧的手法+人工统计的方法来测试。痛点主要有:(1)测试步骤非常繁琐;(2)对于白屏、首屏的结束时间点不同的测... 查看详情

python种子项目ppc保姆级别指导给项目添加测试(代码片段)

...0c;然后开发自己的翻译小项目。这次我们开发函数并编写测试代码,项目中持续加测试,可以让程序质量更高,后期改了直接运行测试,更有保障。对了,还没有安装ppc 查看详情

python种子项目ppc保姆级别指导给项目添加测试(代码片段)

...0c;然后开发自己的翻译小项目。这次我们开发函数并编写测试代码,项目中持续加测试,可以让程序质量更高,后期改了直接运行测试,更有保障。对了,还没有安装ppc 查看详情

大数据开发--zookeeper实现简易配置中心(代码片段)

大数据开发——Zookeeper实现简易配置中心为什么使用ZookeeperZookeeper是一个分布式的,开放源码的分布式协调服务,常在Ha架构,比如Hadoop、Hbase中使用,它是一个分布式应用提供一致性服务的软件,提供的功能... 查看详情

haas700开发动手体验指南(代码片段)

...aaS-Studio集成开发环境页面,按照下图所示的步骤创建测试体验工程。请注意,“工程名字”栏请按照test_demo<月日时分秒>的格式提供,如test_demo1019103005。 步骤三:点击“烧录”按钮将测 查看详情

[alpha阶段]项目展示博客(代码片段)

...ha阶段项目展示1、团队成员介绍bsh负责工作:前端开发及测试,前端负责人。bsh的个人博客byw负责工作:PM,各类文档、博客的撰写,总体计划及督促完成进度。byw的个人博客lqh负责工作:后端开发及测试。lqh的个人博客lw负责... 查看详情

基于springboot2.x开发的简易版图书管理系统(实现对图书的crud)(代码片段)

文章目录:1.项目源码链接2.项目开发前景3.项目大体介绍4.项目整体架构5.项目运行结果图6.结束语1.项目源码链接GitHub链接:https://github.com/2656307671/-SpingBoot-2.x-Book-CRUDGitee码云链接:https://gitee.com/szh-forever-young/sping-boot- 查看详情

自己动手搭建一个简易的springboot环境

什么是springboot?SpringBoot俗称微服务。SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通... 查看详情

web项目的登录窗口的测试(代码片段)

今天咱们继续接上上一篇所讲,开始用项目来练手:给出以下图: 测这个登录窗口:其实比较好测,拿最简单容易想到的,就是什么账号密码均正确;账号为空;密码为空;账号密码均不正确等等,那么我们怎么来用selenium... 查看详情

go语言http包简易入门(代码片段)

说道go语言web编程,必不可少的会使用到net/http包。go语言将web开发需要使用到的很多内容都放在了标准库中——net/http。如何写一个简单的web程序很容易。如下:1packagemain23import(4"fmt"5"net/http"6)78funchello(whttp.ResponseWriter,r*http.... 查看详情