Bladeren bron

init

master
xuxiaofei.666 5 jaren geleden
commit
c21f2fd603
  1. 3
      .gitignore
  2. 4
      README.md
  3. 0
      db.sqlite3
  4. 21
      manage.py
  5. 0
      py_vislib/__init__.py
  6. 16
      py_vislib/asgi.py
  7. 118
      py_vislib/settings/base.py
  8. 15
      py_vislib/settings/local.py
  9. 22
      py_vislib/urls.py
  10. 16
      py_vislib/wsgi.py
  11. 0
      vislib/__init__.py
  12. 3
      vislib/admin.py
  13. 5
      vislib/apps.py
  14. 10
      vislib/middleware.py
  15. 44
      vislib/models.py
  16. 3
      vislib/tests.py
  17. 25
      vislib/urls.py
  18. 278
      vislib/views.py

3
.gitignore

@ -0,0 +1,3 @@
py_vislib/settings/prod.py
*.pyc

4
README.md

@ -0,0 +1,4 @@
# py_vislib
Back end of [vue-data-board](https://github.com/dongsuo/vue-data-board).
## [Document](https://docs.vislib.best)

0
db.sqlite3

21
manage.py

@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'py_vislib.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
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
py_vislib/__init__.py

16
py_vislib/asgi.py

@ -0,0 +1,16 @@
"""
ASGI config for py_vislib 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/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'py_vislib.settings')
application = get_asgi_application()

118
py_vislib/settings/base.py

@ -0,0 +1,118 @@
"""
Django settings for py_vislib project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i6ma-ro$tv1jk=we!liu0(^^mubm$svys0ro+2@$n-8&(*5nj#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# 跨域
# CORS_ORIGIN_ALLOW_ALL = True
# SESSION_COOKIE_SAMESITE = None
# SESSION_COOKIE_SECURE = True
# Application definition
INSTALLED_APPS = [
'vislib.apps.VislibConfig',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'vislib.middleware.SameSiteMiddleware', # position it at the top
'corsheaders.middleware.CorsMiddleware',
'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 = 'py_vislib.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 = 'py_vislib.wsgi.application'
# Database
# ./local.py or ./prod.py
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'

15
py_vislib/settings/local.py

@ -0,0 +1,15 @@
from .base import *
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'vislib',
'USER': 'root',
'PASSWORD': '123456xxf',
'HOST': 'localhost',
'PORT': '3306',
}
}

22
py_vislib/urls.py

@ -0,0 +1,22 @@
"""py_vislib URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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 path, include
urlpatterns = [
path('api/', include('vislib.urls')),
path('admin/', admin.site.urls),
]

16
py_vislib/wsgi.py

@ -0,0 +1,16 @@
"""
WSGI config for py_vislib 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/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'py_vislib.settings')
application = get_wsgi_application()

0
vislib/__init__.py

3
vislib/admin.py

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
vislib/apps.py

@ -0,0 +1,5 @@
from django.apps import AppConfig
class VislibConfig(AppConfig):
name = 'vislib'

10
vislib/middleware.py

@ -0,0 +1,10 @@
from django.utils.deprecation import MiddlewareMixin
class SameSiteMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if 'sessionid' in response.cookies:
response.cookies['sessionid']['samesite'] = 'None'
if 'csrftoken' in response.cookies:
response.cookies['csrftoken']['samesite'] = 'None'
return response

44
vislib/models.py

@ -0,0 +1,44 @@
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
def default_datetime():
now = timezone.now()
return now
# Create your models here.
class Chart(models.Model):
chart_id=models.CharField(max_length=64, primary_key=True)
chart_name=models.CharField(max_length=128)
desc=models.CharField(max_length=512, null=True)
content=models.TextField()
is_private=models.BooleanField()
status=models.IntegerField()
creator=models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(db_index=True, default=default_datetime)
updated_at = models.DateTimeField(db_index=True, null=False)
class Dashboard(models.Model):
dashboard_id=models.CharField(max_length=64, primary_key=True)
name=models.CharField(max_length=128)
desc=models.CharField(max_length=512, null=True)
content=models.TextField()
is_private=models.BooleanField()
status=models.IntegerField()
creator=models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(db_index=True, default=default_datetime)
updated_at = models.DateTimeField(db_index=True, null=False)
class ChartBoardMap(models.Model):
chart=models.ForeignKey(Chart, on_delete=models.CASCADE)
dashboard=models.ForeignKey(Dashboard, on_delete=models.CASCADE)
id=models.CharField(max_length=64, primary_key=True)
created_at = models.DateTimeField(db_index=True, default=default_datetime)
updated_at = models.DateTimeField(db_index=True, null=False)
class BoardOrder(models.Model):
creator=models.ForeignKey(User, on_delete=models.CASCADE)
order=models.TextField()
id=models.CharField(max_length=64, primary_key=True)
created_at = models.DateTimeField(db_index=True, default=default_datetime)
updated_at = models.DateTimeField(db_index=True, null=False)

3
vislib/tests.py

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

25
vislib/urls.py

@ -0,0 +1,25 @@
from django.urls import path
from . import views
urlpatterns = [
path('user/info', views.user, name='userinfo'),
path('user/signup', views.userSignup, name='signup'),
path('user/login', views.userLogin, name='login'),
path('user/logout', views.userLogout, name='logout'),
path('exesql', views.execSql, name='execSql'),
path('chart/list', views.chartList, name="chartList"),
path('chart/create', views.createChart, name="createChart"),
path('chart/update', views.updateChart, name="updateChart"),
path('chart/delete', views.deleteChart, name="deleteChart"),
path('chart/<uuid:chartId>', views.chartDetail, name="chartDetail"),
path('chartboardmap/boardbychart', views.boardByChart, name="boardByChart"),
path('dashboard/create', views.createDashboard, name="createDashboard"),
path('dashboard/update', views.updateDashboard, name="updateDashboard"),
path('dashboard/delete', views.deleteDashboard, name="deleteDashboard"),
path('dashboard/<uuid:dashboardId>', views.dashboardDetail, name="dashboardDetail"),
path('dashboard/list', views.dashboardList, name="dashboardList"),
path('dashboard/order', views.dashboardOrder, name="dashboardOrder"),
path('chartboard/map', views.chartBoardMap, name="chartBoardMap"),
path('chartboard/unmap', views.chartBoardUnmap, name="chartBoardUnmap"),
path('chartboardmap/chartbydashboard', views.chartByBoard, name="chartByBoard"),
]

278
vislib/views.py

@ -0,0 +1,278 @@
import json
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from MySQLdb import _mysql
from django.core import serializers
from vislib.models import Chart, Dashboard, ChartBoardMap, BoardOrder
from django.utils import timezone
import uuid
# Create your views here.
def default_datetime():
now = timezone.now()
return now
def index(request):
return HttpResponse('hello python and django')
@csrf_exempt
def user(request):
if request.user.is_authenticated:
username = request.user.get_username()
return JsonResponse({'code': 20000, 'data': {'username': username}})
else:
return JsonResponse({'code': 40000, 'message': 'Please login'})
@csrf_exempt
def userSignup(request):
body = json.loads(request.body)
if User.objects.filter(username=body['userName']).exists():
return JsonResponse({'code': 10000, 'message': 'User Name ' + body['userName'] + ' is Already Tabken.'})
if User.objects.filter(email=body['email']).exists():
return JsonResponse({'code': 10000, 'message': 'Email ' + body['emaul'] + ' is Registered.'})
user = User.objects.create_user(body['userName'], body['email'], body['password'])
user.first_name=body['userName']
user.save()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def userLogin(request):
body = json.loads(request.body)
user = authenticate(request, username=body['userName'], password=body['password'])
if user is not None:
login(request, user)
return JsonResponse({'code': 20000, 'message': 'success'})
else:
return JsonResponse({'code': 10000, 'message': 'Name or Password Not Correct, Please Try Again.'})
@csrf_exempt
def userLogout(request):
logout(request)
return JsonResponse({'code': 20000, 'message': 'success'})
def execSql(request):
db=_mysql.connect( "127.0.0.1", "root", "123456xxf", "sql12298540", charset='utf8')
db.query(request.GET['sql'])
data = db.store_result().fetch_row(maxrows=0, how=2)
db.close()
json_data = []
for index in range(len(data)):
row = data[index]
json_data.append({})
for key in row:
if(key.find('.')>0):
column = (key.split('.'))[1]
else:
column = key
if isinstance(row[key], bytes):
json_data[index][column] = row[key].decode('UTF-8')
else:
json_data[index][column] = row[key]
response = {
'code': 20000,
'message': 'success',
'data': json_data
}
return JsonResponse(response)
@csrf_exempt
def chartList(request):
charts = Chart.objects.filter(creator=request.user)
charts = serializers.serialize('json', charts)
charts = json.loads(charts)
chartArr = []
for chart in charts:
chart['fields']['chart_id'] = chart['pk']
chartArr.append(chart['fields'])
return JsonResponse({'code': 20000, 'data': chartArr})
@csrf_exempt
def createChart(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
chart_name = body['chart_name']
desc = body.get('desc', None)
content = body['content']
creator = request.user
chart_id = uuid.uuid4()
Chart.objects.create(
chart_id=chart_id,
chart_name=chart_name,
desc=desc,
content=json.dumps(content),
creator=creator,
is_private=True,
status=1,
updated_at=default_datetime()
)
return JsonResponse({'code': 20000, 'message': 'success', 'data': {'id': chart_id}})
@csrf_exempt
def updateChart(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
chart = Chart.objects.get(chart_id=body['id'])
chart.chart_name = body['chart_name']
chart.desc = body['desc']
chart.content = json.dumps(body['content'])
chart.updated_at = default_datetime()
chart.save()
return JsonResponse({'code': 20000, 'message': 'success', 'data': {'id': body['id']}})
@csrf_exempt
def deleteChart(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
chart = Chart.objects.get(chart_id=body['chart_id'])
chart.delete()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def chartDetail(request, chartId):
chartDetail = Chart.objects.get(chart_id=chartId)
chartDetail = serializers.serialize('json', [chartDetail])
chartDetail = json.loads(chartDetail)[0]
return JsonResponse({'code': 20000, 'message': 'success', 'data':chartDetail['fields'] })
@csrf_exempt
def createDashboard(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
name = body['name']
desc = body.get('desc', '')
content = body.get('content', '')
creator = request.user
dashboard_id = uuid.uuid4()
Dashboard.objects.create(
dashboard_id=dashboard_id,
name=name,
desc=desc,
content=json.dumps(body.get('content', {})),
creator=creator,
is_private=True,
status=1,
updated_at=default_datetime()
)
return JsonResponse({'code': 20000, 'message': 'success', 'data': {'id': dashboard_id}})
@csrf_exempt
def updateDashboard(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
dashboard_id = body.get('dashboard_id')
board = Dashboard.objects.get(dashboard_id=dashboard_id)
board.name = body['name']
board.desc = body.get('desc', '')
board.content = json.dumps(body.get('content', {}))
board.updated_at = default_datetime()
board.save()
return JsonResponse({'code': 20000, 'message': 'success', 'data': {'id': dashboard_id}})
@csrf_exempt
def dashboardDetail(request, dashboardId):
dashboard = Dashboard.objects.get(dashboard_id= dashboardId)
dashboard = serializers.serialize('json',[dashboard])
dashboard = json.loads(dashboard)[0]
dashboard['fields']['dashboard_id'] = dashboardId
return JsonResponse({'code': 20000, 'message': 'success', 'data': dashboard['fields']})
@csrf_exempt
def deleteDashboard(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
dashboard = Dashboard.objects.get(dashboard_id=body['dashboard_id'])
dashboard.delete()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def dashboardList(request):
dashboards = Dashboard.objects.filter(creator=request.user)
dashboards = serializers.serialize('json', dashboards)
dashboards = json.loads(dashboards)
dbArr = []
for db in dashboards:
db['fields']['dashboard_id'] = db['pk']
db['fields']['content'] = json.loads(db['fields']['content'])
dbArr.append(db['fields'])
order = BoardOrder.objects.filter(creator=request.user)
order = json.loads(serializers.serialize('json', order))
if len(order)!=0:
order = order[0]
order = order['fields']['order']
order = order.split('|')
else:
order = []
return JsonResponse({'code': 20000, 'message': 'success', 'data':{'dashboards': dbArr, 'order': order} })
@csrf_exempt
def chartBoardMap(request):
body = request.body.decode('utf-8')
body = json.loads(body)
dashboard = Dashboard.objects.get(dashboard_id=body['dashboard_id'])
chart = Chart.objects.get(chart_id=body['chart_id'])
ChartBoardMap.objects.create(
id=uuid.uuid4(),
chart=chart,
dashboard=dashboard,
updated_at=default_datetime()
)
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def chartBoardUnmap(request):
body = request.body.decode('utf-8')
body = json.loads(body)
chart_id = body['chart_id']
dashboard_id = body['dashboard_id']
map = ChartBoardMap.objects.get(chart=chart_id, dashboard=dashboard_id)
map.delete()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def chartByBoard(request):
map = ChartBoardMap.objects.filter(dashboard=request.GET['dashboard_id'])
charts = []
for item in map:
chart = serializers.serialize('json', [item.chart])
chart = json.loads(chart)[0]
chart['fields']['chart_id'] = chart['pk']
charts.append(chart['fields'])
return JsonResponse({'code': 20000, 'message': 'success', 'data': charts})
@csrf_exempt
def boardByChart(request):
map = ChartBoardMap.objects.filter(chart=request.GET['chart_id'])
boards = []
for item in map:
board = serializers.serialize('json', [item.dashboard])
board = json.loads(board)[0]
board['fields']['dashboard_id'] = board['pk']
boards.append(board['fields'])
return JsonResponse({'code': 20000, 'message': 'success', 'data': boards})
@csrf_exempt
def dashboardOrder(request):
body = json.loads(request.body)
split = '|'
orderStr = split.join(body['order'])
order = BoardOrder.objects.filter(creator=request.user)
if order:
order[0].order = orderStr
order[0].save()
else:
BoardOrder.objects.create(
order=orderStr,
id=uuid.uuid4(),
creator=request.user,
updated_at=default_datetime()
)
return JsonResponse({'code': 20000, 'message': 'success'})
Laden…
Annuleren
Opslaan