Commit c6502ec3 authored by 王超's avatar 王超

CMS2.0打包程序

parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.10 (CMSDjango)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (CMSDjango)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/CMSDjango.iml" filepath="$PROJECT_DIR$/.idea/CMSDjango.iml" />
</modules>
</component>
</project>
\ No newline at end of file
"""
ASGI config for CMSDjango project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMSDjango.settings')
application = get_asgi_application()
"""
Django settings for CMSDjango project.
Generated by 'django-admin startproject' using Django 5.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-mf4ma2=ej088vv5&rhvlp-4$xagchqcv9xpfy2wb0)a_)!1r)v'
#调试模式,调试代码期间可以打开,放生产允许时建议关闭
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#添加允许访问的主机IP
ALLOWED_HOSTS = ['192.168.1.188','127.0.0.1','192.168.4.74','192.168.4.72']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"polls",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'CMSDjango.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'CMSDjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# settings.py
#CMS gitlab接口请求参数
GITLAB_TOKEN = 'glpat-oVvR3Y-9t_RppWpsGkM4'
GITLAB_PROJECT_ID = '442'
#生产环境python manage.py runserver
GITLAB_PIPELINE_TRIGGER_URL = f'https://gitlab.syc-cms.com/api/v4/projects/{GITLAB_PROJECT_ID}/trigger/pipeline'
#测试环境
#GITLAB_PIPELINE_TRIGGER_URL = f'http://127.0.0.1:8000/api/v4/projects/442/trigger/pipeline'
GITLAB_REF = 'main' # 你想要触发的分支
GITLAB_TRIGGER_TOKEN = 'glptt-928d46824b5563e8f5209fb3f3c053fe496ece92'
"""
URL configuration for CMSDjango project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls),
path("polls/", include("polls.urls")),
]
"""
WSGI config for CMSDjango project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMSDjango.settings')
application = get_wsgi_application()
File added
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMSDjango.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
# 配置IP地址和端口
#sys.argv += ['192.168.1.188:8000']
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
\ No newline at end of file
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
\ No newline at end of file
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
\ No newline at end of file
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
QA CI PAGE
</title>
</head>
<body>
<h1>
Trigger GitLab Pipeline to Generate the CMS2.0 test package
</h1>
<h3>
gitlab task status: {{messages}}
</h3>
<div>
<p>操作说明:在触发gitlab构建测试包前,需选择分支、填写前端变量、后端变量,前端变量及后端变量每个版本可能会发生变化,在填写前请和研发确认。</p>
</div>
<form method="post" action="/polls/trigger_pipeline/">
{% csrf_token %}
<label for="ref">选择分支:</label>
<select id="ref" name="ref">
<option value="master">master</option>
<option value="dev">dev</option>
<option value="feature-branch">feature-branch</option>
</select>
<label for="build_frontend_ref">前端变量:</label>
<input type="text" id="build_frontend_ref" name="build_frontend_ref" required>
<label for="build_backend_ref">后端变量:</label>
<input type="text" id="build_backend_ref" name="build_backend_ref" required>
<button type="submit">
Trigger Pipeline
</button>
</form>
<div class="container">
<h1 class="mt-5">GitLab Pipelines</h1>
<h3>
<table class="table table-striped mt-3" border="1">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Ref</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{% for pipeline in pipelines %}
<tr>
<td>{{ pipeline.id }}</td>
<td>{{ pipeline.status }}</td>
<td>{{ pipeline.ref }}</td>
<td>{{ pipeline.created_at }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</h3>
</div>
</body>
</html>
\ No newline at end of file
[
{"id":16799,"iid":10,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"trigger","created_at":"2024-06-11T12:02:32.454+08:00","updated_at":"2024-06-11T12:02:55.585+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16799","name":null},
{"id":16798,"iid":9,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"trigger","created_at":"2024-06-11T11:54:56.171+08:00","updated_at":"2024-06-11T11:55:08.967+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16798","name":null},
{"id":16797,"iid":8,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"trigger","created_at":"2024-06-11T11:24:07.093+08:00","updated_at":"2024-06-11T11:24:27.261+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16797","name":null},
{"id":16785,"iid":7,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"trigger","created_at":"2024-06-11T10:13:36.761+08:00","updated_at":"2024-06-11T10:14:02.101+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16785","name":null},
{"id":16784,"iid":6,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"trigger","created_at":"2024-06-11T10:09:21.499+08:00","updated_at":"2024-06-11T10:10:18.842+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16784","name":null},
{"id":16753,"iid":5,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"web","created_at":"2024-06-06T16:25:10.166+08:00","updated_at":"2024-06-06T16:25:34.688+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16753","name":null},
{"id":16725,"iid":4,"project_id":583,"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c","ref":"main","status":"canceled","source":"push","created_at":"2024-06-06T10:36:16.111+08:00","updated_at":"2024-06-06T10:37:09.584+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16725","name":null},
{"id":16708,"iid":3,"project_id":583,"sha":"13d4f25547c11760adec3e76f1eb6e7bca98a4bb","ref":"main","status":"canceled","source":"push","created_at":"2024-06-04T15:56:22.871+08:00","updated_at":"2024-06-04T15:57:08.036+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16708","name":null},
{"id":16707,"iid":2,"project_id":583,"sha":"d5de56d2538ece71990ac307e212a0f4a2645b4a","ref":"main","status":"canceled","source":"push","created_at":"2024-06-04T14:30:22.635+08:00","updated_at":"2024-06-04T15:56:23.256+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16707","name":null},
{"id":16706,"iid":1,"project_id":583,"sha":"6e5797dfe6ea0c4a0b19ec7a8f8518a72f680e65","ref":"main","status":"canceled","source":"push","created_at":"2024-06-04T13:43:50.032+08:00","updated_at":"2024-06-04T14:24:47.131+08:00","web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16706","name":null},
{"id":16799,
"iid":10,
"project_id":583,
"sha":"a8e5f5cb25c44a201fc74c4b3e504f401e9f463c",
"ref":"main",
"status":"canceled",
"source":"trigger",
"created_at":"2024-06-11T12:02:32.454+08:00",
"updated_at":"2024-06-11T12:02:55.585+08:00",
"web_url":"https://gitlab.syc-cms.com/gitlab_qa/cms_ci_test/-/pipelines/16799",
"name":null},
{"id":16824,
"iid":7406,
"project_id":56,
"sha":"cf3fd9120973a4892deab3e8c966a99c08ef9e20",
"ref":"master",
"status":"skipped",
"source":"trigger",
"created_at":"2024-06-11T14:55:56.240+08:00",
"updated_at":"2024-06-11T14:55:58.543+08:00",
"web_url":"https://gitlab.syc-cms.com/cms/cms/-/pipelines/16824","name":null},
{"id":16824,
"iid":7406,
"project_id":56,
"sha":"cf3fd9120973a4892deab3e8c966a99c08ef9e20",
"ref":"master",
"status":"skipped",
"source":"trigger",
"created_at":"2024-06-11T14:55:56.240+08:00",
"updated_at":"2024-06-11T14:55:58.543+08:00",
"web_url":"https://gitlab.syc-cms.com/cms/cms/-/pipelines/16824",
"before_sha":"0000000000000000000000000000000000000000",
"tag":false,
"yaml_errors":null,
"user":{"id":2,"username":"yuhang.lai","name":"赖育杭","state":"active","locked":false,"avatar_url":"https://secure.gravatar.com/avatar/c4e02c749e1e2a28fc7b946f4fe9dba6?s=80\u0026d=identicon","web_url":"https://gitlab.syc-cms.com/yuhang.lai"},
"started_at":null,
"finished_at":null,
"committed_at":null,
"duration":null,
"queued_duration":null,
"coverage":null,
"detailed_status":{
"icon":"status_skipped",
"text":"Skipped",
"label":"skipped",
"group":"skipped",
"tooltip":"skipped",
"has_details":false,
"details_path":"/cms/cms/-/pipelines/16824",
"illustration":null,
"favicon":"/assets/ci_favicons/favicon_status_skipped-0b9c5e543588945e8c4ca57786bbf2d0c56631959c9f853300392d0315be829b.png"
},
"name":null}
]
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.urls import path
from . import views
from .views import trigger_pipeline
app_name = "polls"
urlpatterns = [
path("", views.index, name="index"),
path("<int:question_id>/",views.detail,name="detail"),
path("<int:question_id>/results/",views.results,name="results"),
path("<int:question_id>/vote/",views.vote,name="vote"),
path("trigger/", views.trigger_page, name="trigger_page"),
path("trigger_pipeline/", views.trigger_pipeline, name="trigger_pipeline"),
]
import json
from django.shortcuts import get_object_or_404,render
from django.db.models import F
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from .models import Question,Choice
from django.template import loader
from django.http import Http404
from django.urls import reverse
import requests
from django.conf import settings
def index(request):
latest_question_list = Question.objects.order_by("-pub_date")[:5]
#template = loader.get_template("polls/index.html")#
context = {
"latest_question_list":latest_question_list,
"latest_question_list":latest_question_list,
}
return render(request,"polls/index.html",context)
def detail(request, question_id):
'''try:
question = Question.objects.get(pk = question_id)
except Question.DoesNotExist:
raise Http404("Question does not exits")'''
question = get_object_or_404(Question,pk = question_id)
return render(request,"polls/detail.html",{"question":question})
def results(request, question_id):
question = get_object_or_404(Question,pk=question_id)
return render(request,"polls/results.html",{"question":question})
def vote(request, question_id):
question = get_object_or_404(Question,pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST["choice"])
except(KeyError,Choice.DoesNotExist):
return render(
request,
"polls/detail.html",
{
"question":question,
"error_message":"You didn't select a choice.",
}
)
else:
selected_choice.votes = F("votes")+1
selected_choice.save()
return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))
def trigger_pipeline(request):
if request.method == "POST":
url = settings.GITLAB_PIPELINE_TRIGGER_URL #gitlab接口请求地址
ref = request.POST.get('ref') #需要选择打包的分支
build_frontend_ref = request.POST.get('build_frontend_ref') #前端变量
build_backend_ref = request.POST.get('build_backend_ref') #后端变量
headers = {
'PRIVATE-TOKEN': settings.GITLAB_TOKEN,
}
data = {
'token': settings.GITLAB_TRIGGER_TOKEN,
'ref': ref,
'variables[BUILD_FRONTEND_REF]': build_frontend_ref,
'variables[BUILD_BACKEND_REF]': build_backend_ref
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 201:
print("trigger success")
messages = "trigger success"
url = reverse("polls:trigger_page") + f'?messages={messages}'
return HttpResponseRedirect(url)
else:
print("trigger failed")
messages = "trigger failed"
url = reverse("polls:trigger_page") + f'?messages={messages}'
return HttpResponseRedirect(url)
else:
print("wrong method")
messages = "wrong method"
url = reverse("polls:trigger_page") + f'?messages={messages}'
return HttpResponseRedirect(url)
def trigger_page(request):
message = request.GET.get('messages')
if message == None:
message = 'not ready'
print(message)
context = {
"pipelines":pipeline_list(),
"messages":message
}
#print(context["messages"])
return render(request, 'polls/trigger_pipeline.html',context)
def pipeline_list():
url = f'https://gitlab.syc-cms.com/api/v4/projects/{settings.GITLAB_PROJECT_ID}/pipelines'
headers = {
'PRIVATE-TOKEN':settings.GITLAB_TOKEN,
}
response = requests.get(url,headers=headers)
response_dict = json.loads(response.text)
if "error" in response_dict:
print("in pipeline_list() method get_pipelines_response:" + response.text)
else:
all_pipelines = response.json()
pipelines = [pipeline for pipeline in all_pipelines if pipeline['source']=='trigger']
return pipelines
'''context = {
"pipelines":pipelines,
}'''
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment