Browse Source

Feat/add data source

master
东索 5 years ago
committed by GitHub
parent
commit
397f2e8321
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      .pylintrc
  2. 57
      common/utils/aes.py
  3. 2
      py_vislib/settings/local.py
  4. 2
      vislib/admin.py
  5. 6
      vislib/middleware.py
  6. 66
      vislib/migrations/0001_initial.py
  7. 42
      vislib/migrations/0002_sourcedatabase_sourcedatatable.py
  8. 18
      vislib/migrations/0003_auto_20200415_0913.py
  9. 23
      vislib/migrations/0004_auto_20200415_0920.py
  10. 25
      vislib/migrations/0005_auto_20200415_0934.py
  11. 18
      vislib/migrations/0006_sourcedatatable_status.py
  12. 20
      vislib/migrations/0007_chart_source_id.py
  13. 18
      vislib/migrations/0008_auto_20200425_0917.py
  14. 0
      vislib/migrations/__init__.py
  15. 81
      vislib/models.py
  16. 2
      vislib/tests.py
  17. 54
      vislib/urls.py
  18. 75
      vislib/views/chart.py
  19. 129
      vislib/views/dashboard.py
  20. 173
      vislib/views/source.py
  21. 43
      vislib/views/user.py
  22. 64
      vislib/views/views.py

5
.pylintrc

@ -0,0 +1,5 @@
[MASTER]
ignore=migrations
disable=
C0114, # missing-module-docstring

57
common/utils/aes.py

@ -0,0 +1,57 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#@author: rui.xu
#这里使用pycrypto‎库
#按照方法:easy_install pycrypto‎
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from django.conf import settings
class prpcrypt():
def __init__(self,key):
self.key = key
self.mode = AES.MODE_CBC
#加密函数,如果text不足16位就用空格补足为16位,
#如果大于16当时不是16的倍数,那就补足为16的倍数。
def encrypt(self,text):
cryptor = AES.new(self.key,self.mode, b'0000000000000000')
#这里密钥key 长度必须为16(AES-128),
#24(AES-192),或者32 (AES-256)Bytes 长度
#目前AES-128 足够目前使用
# nonce = cryptor.nonce
length = 32
count = len(text)
if count < length:
add = (length-count)
#\0 backspace
text = text + ('\0' * add)
elif count > length:
add = (length-(count % length))
text = text + ('\0' * add)
print(text)
self.ciphertext = cryptor.encrypt(text.encode("utf8"))
#因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
#所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(self.ciphertext)
#解密后,去掉补足的空格用strip() 去掉
def decrypt(self,text):
cryptor = AES.new(self.key,self.mode,b'0000000000000000')
plain_text = cryptor.decrypt(a2b_hex(text)).decode("utf8")
return plain_text.rstrip('\0')
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥
if __name__ == '__main__':
# for test
print(settings.CRYPT_KEY)
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥
import sys
str = sys.argv[1]
e = pc.encrypt(str) #加密
print("加密:",e)
d = pc.decrypt(e) #解密
print("解密:",d)

2
py_vislib/settings/local.py

@ -13,3 +13,5 @@ DATABASES = {
'PORT': '3306',
}
}
CRYPT_KEY = 'keyskeyskeyskeys'

2
vislib/admin.py

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

6
vislib/middleware.py

@ -4,7 +4,7 @@ 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'
response.cookies['sessionid']['samesite'] = 'None'
if 'csrftoken' in response.cookies:
response.cookies['csrftoken']['samesite'] = 'None'
return response
response.cookies['csrftoken']['samesite'] = 'None'
return response

66
vislib/migrations/0001_initial.py

@ -0,0 +1,66 @@
# Generated by Django 3.0.4 on 2020-04-02 03:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import vislib.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Chart',
fields=[
('chart_id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('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()),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Dashboard',
fields=[
('dashboard_id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('name', models.CharField(max_length=128)),
('desc', models.CharField(max_length=512, null=True)),
('content', models.TextField()),
('is_private', models.BooleanField()),
('status', models.IntegerField()),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ChartBoardMap',
fields=[
('id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('chart', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vislib.Chart')),
('dashboard', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vislib.Dashboard')),
],
),
migrations.CreateModel(
name='BoardOrder',
fields=[
('order', models.TextField()),
('id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

42
vislib/migrations/0002_sourcedatabase_sourcedatatable.py

@ -0,0 +1,42 @@
# Generated by Django 3.0.4 on 2020-04-14 02:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import vislib.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('vislib', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='SourceDataBase',
fields=[
('host', models.CharField(max_length=32)),
('port', models.IntegerField()),
('username', models.CharField(max_length=32)),
('password', models.CharField(max_length=64)),
('database', models.CharField(max_length=32)),
('id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='SourceDataTable',
fields=[
('table', models.CharField(max_length=32)),
('id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(db_index=True, default=vislib.models.default_datetime)),
('updated_at', models.DateTimeField(db_index=True)),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('database', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vislib.SourceDataBase')),
],
),
]

18
vislib/migrations/0003_auto_20200415_0913.py

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-04-15 01:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vislib', '0002_sourcedatabase_sourcedatatable'),
]
operations = [
migrations.RenameField(
model_name='sourcedatabase',
old_name='id',
new_name='source_id',
),
]

23
vislib/migrations/0004_auto_20200415_0920.py

@ -0,0 +1,23 @@
# Generated by Django 3.0.4 on 2020-04-15 01:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vislib', '0003_auto_20200415_0913'),
]
operations = [
migrations.AddField(
model_name='sourcedatabase',
name='is_private',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='sourcedatabase',
name='status',
field=models.IntegerField(default=1),
),
]

25
vislib/migrations/0005_auto_20200415_0934.py

@ -0,0 +1,25 @@
# Generated by Django 3.0.4 on 2020-04-15 01:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vislib', '0004_auto_20200415_0920'),
]
operations = [
migrations.AddField(
model_name='sourcedatabase',
name='base_alias',
field=models.CharField(default='', max_length=32),
preserve_default=False,
),
migrations.AddField(
model_name='sourcedatatable',
name='table_alias',
field=models.CharField(default='', max_length=32),
preserve_default=False,
),
]

18
vislib/migrations/0006_sourcedatatable_status.py

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-04-15 15:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vislib', '0005_auto_20200415_0934'),
]
operations = [
migrations.AddField(
model_name='sourcedatatable',
name='status',
field=models.IntegerField(default=1),
),
]

20
vislib/migrations/0007_chart_source_id.py

@ -0,0 +1,20 @@
# Generated by Django 3.0.4 on 2020-04-17 15:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('vislib', '0006_sourcedatatable_status'),
]
operations = [
migrations.AddField(
model_name='chart',
name='source_id',
field=models.ForeignKey(default='ce2f9129-c4a8-40fe-934f-1385824ca23c', on_delete=django.db.models.deletion.CASCADE, to='vislib.SourceDataBase'),
preserve_default=False,
),
]

18
vislib/migrations/0008_auto_20200425_0917.py

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-04-25 01:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vislib', '0007_chart_source_id'),
]
operations = [
migrations.AlterField(
model_name='sourcedatabase',
name='password',
field=models.CharField(max_length=256),
),
]

0
vislib/migrations/__init__.py

81
vislib/models.py

@ -2,43 +2,68 @@ from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
def default_datetime():
now = timezone.now()
def default_datetime():
now = timezone.now()
return now
class SourceDataBase(models.Model):
host = models.CharField(max_length=32)
port = models.IntegerField()
username = models.CharField(max_length=32)
password = models.CharField(max_length=256)
database = models.CharField(max_length=32)
base_alias = models.CharField(max_length=32)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
source_id = models.CharField(max_length=64, primary_key=True)
is_private = models.BooleanField(default=True)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(db_index=True, default=default_datetime)
updated_at = models.DateTimeField(db_index=True, null=False)
class SourceDataTable(models.Model):
database = models.ForeignKey(SourceDataBase, on_delete=models.CASCADE)
table = models.CharField(max_length=32)
table_alias = models.CharField(max_length=32)
status = models.IntegerField(default=1)
creator = models.ForeignKey(User, 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)
# 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)
chart_id = models.CharField(max_length=64, primary_key=True)
chart_name = models.CharField(max_length=128)
source_id = models.ForeignKey(SourceDataBase, on_delete=models.CASCADE)
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)
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)
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)
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)

2
vislib/tests.py

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

54
vislib/urls.py

@ -1,25 +1,37 @@
from django.urls import path
from . import views
from .views import user, chart, dashboard, views, source
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"),
path('user/info', user.userInfo, name='userinfo'),
path('user/signup', user.userSignup, name='signup'),
path('user/login', user.userLogin, name='login'),
path('user/logout', user.userLogout, name='logout'),
path('exesql', views.execSql, name='execSql'),
path('chart/list', chart.chartList, name="chartList"),
path('chart/create', chart.createChart, name="createChart"),
path('chart/update', chart.updateChart, name="updateChart"),
path('chart/delete', chart.deleteChart, name="deleteChart"),
path('chart/<uuid:chartId>', chart.chartDetail, name="chartDetail"),
path('chartboardmap/boardbychart', dashboard.boardByChart, name="boardByChart"),
path('dashboard/create', dashboard.createDashboard, name="createDashboard"),
path('dashboard/update', dashboard.updateDashboard, name="updateDashboard"),
path('dashboard/delete', dashboard.deleteDashboard, name="deleteDashboard"),
path('dashboard/<uuid:dashboardId>', dashboard.dashboardDetail, name="dashboardDetail"),
path('dashboard/list', dashboard.dashboardList, name="dashboardList"),
path('dashboard/order', dashboard.dashboardOrder, name="dashboardOrder"),
path('chartboard/map', dashboard.chartBoardMap, name="chartBoardMap"),
path('chartboard/unmap', dashboard.chartBoardUnmap, name="chartBoardUnmap"),
path('chartboardmap/chartbydashboard', dashboard.chartByBoard, name="chartByBoard"),
path('source/list', source.sourceList, name="sourceList"),
path('source/create', source.createSource, name="createSource"),
path('source/update', source.updateSource, name="updateSource"),
path('source/delete', source.deleteSource, name="deleteSource"),
path('source/<uuid:sourceId>', source.sourceDetail, name="sourceDetail"),
path('source/tables/<uuid:sourceId>', source.sourceTables, name="sourceTables"),
path('source/tables/save', source.sourceTableSave, name="sourceTableSave"),
path('source/tables/<uuid:sourceId>/linked', source.sourceLinkedTables, name="sourceLinkedTables"),
]

75
vislib/views/chart.py

@ -0,0 +1,75 @@
import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from vislib.models import Chart, SourceDataBase
from django.utils import timezone
import uuid
def default_datetime():
now = timezone.now()
return now
@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']
source_id = SourceDataBase.objects.get(source_id=body['source_id'])
creator = request.user
chart_id = uuid.uuid4()
Chart.objects.create(
chart_id=chart_id,
source_id=source_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.source_id = SourceDataBase.objects.get(source_id=body['source_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'] })

129
vislib/views.py → vislib/views/dashboard.py

@ -1,145 +1,16 @@
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')

173
vislib/views/source.py

@ -0,0 +1,173 @@
import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from vislib.models import SourceDataBase, SourceDataTable
from django.utils import timezone
from common.utils.aes import pc
from MySQLdb import _mysql
import uuid
def default_datetime():
now = timezone.now()
return now
@csrf_exempt
def createSource(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
host = body['host']
port = body.get('port', 3306)
username = body.get('username')
password = pc.encrypt(body.get('password')).decode('utf-8')
database = body.get('database')
base_alias = body.get('base_alias')
creator = request.user
source_id = uuid.uuid4()
SourceDataBase.objects.create(
source_id=source_id,
host=host,
port=port,
username=username,
password=password,
database=database,
base_alias=base_alias,
creator=creator,
is_private=True,
status=1,
updated_at=default_datetime()
)
return JsonResponse({'code': 20000, 'message': 'success', 'data': {'id': source_id}})
@csrf_exempt
def deleteSource(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
source = SourceDataBase.objects.get(source_id=body['source_id'])
source.delete()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def updateSource(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
source = SourceDataBase.objects.get(source_id=body['source_id'])
source.host = body['host']
source.port = body.get('port', 3306)
source.username = body.get('username')
if body.get('password'):
source.password = pc.encrypt(body.get('password'))
else:
source = serializers.serialize('json', [source])
source = json.loads(source)[0]['fields']
source.password = source['password']
source.database = body.get('database')
source.base_alias = body.get('base_alias')
source.save()
return JsonResponse({'code': 20000, 'message': 'success'})
@csrf_exempt
def sourceList(request):
sourceList = SourceDataBase.objects.filter(creator=request.user)
sourceList = serializers.serialize('json', sourceList)
sourceList = json.loads(sourceList)
sourceArr = []
for source in sourceList:
source['fields']['source_id'] = source['pk']
source['fields']['password'] = None
sourceArr.append(source['fields'])
return JsonResponse({'code': 20000, 'data': sourceArr})
@csrf_exempt
def sourceDetail(request, sourceId):
sourceDetail = SourceDataBase.objects.get(source_id=sourceId)
sourceDetail = serializers.serialize('json', [sourceDetail])
sourceDetail = json.loads(sourceDetail)[0]
return JsonResponse({'code': 20000, 'message': 'success', 'data':sourceDetail['fields'] })
@csrf_exempt
def sourceTables(request, sourceId):
try:
tables = SourceDataTable.objects.get(database=sourceId)
tables = serializers.serialize('json', [tables])
tables = json.loads(tables)
json_data = []
for table in tables:
json_data.append(table['fields'])
except:
source = SourceDataBase.objects.get(source_id=sourceId)
source = serializers.serialize('json', [source])
source = json.loads(source)[0]['fields']
password = source['password'].encode(('utf-8'))
print(password)
host = source['host']
username = source['username']
port = source['port']
password = pc.decrypt(password)
database = source['database']
print(password)
db=_mysql.connect(
host=host,
port=int(port),
user=username,
passwd=password,
db=database,
charset='utf8'
)
db.query('show tables;')
tables = db.store_result().fetch_row(maxrows=0, how=2)
db.close()
json_data = list(tables[0].values())
for i, table in enumerate(json_data):
json_data[i] = {
'table': table.decode('utf-8'),
'status': 0
}
return JsonResponse({'code': 20000, 'message': 'success', 'data': json_data })
@csrf_exempt
def sourceTableSave(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
print(body)
source_id = body['source_id']
SourceDataTable.objects.filter(database=source_id).delete()
source = SourceDataBase.objects.get(source_id=source_id)
for table in body['tables']:
tableConfig = SourceDataTable.objects.create(
id=uuid.uuid4(),
database=source,
table=table['table'],
table_alias=table['table_alias'],
creator=request.user,
status=table['status'],
updated_at=default_datetime()
)
tableConfig.save()
return JsonResponse({'code': 20000, 'message': 'success' })
@csrf_exempt
def sourceLinkedTables(request, sourceId):
try:
tables = SourceDataTable.objects.get(database=sourceId)
tables = serializers.serialize('json', [tables])
tables = json.loads(tables)
json_data = []
for table in tables:
json_data.append(table['fields'])
except:
json_data = []
return JsonResponse({'code': 20000, 'message': 'success', 'data': json_data })

43
vislib/views/user.py

@ -0,0 +1,43 @@
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
@csrf_exempt
def userInfo(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'})

64
vislib/views/views.py

@ -0,0 +1,64 @@
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from MySQLdb import _mysql
from django.core import serializers
from vislib.models import SourceDataBase, SourceDataTable
from django.utils import timezone
from common.utils.aes import pc
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 execSql(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
sql = body['sql']
sourceId = body['source_id']
source = SourceDataBase.objects.get(source_id=sourceId)
source = serializers.serialize('json', [source])
source = json.loads(source)[0]['fields']
host = source['host']
username = source['username']
port = source['port']
password = pc.decrypt(source['password'])
database = source['database']
db=_mysql.connect(
host=host,
port=int(port),
user=username,
passwd=password,
db=database,
charset='utf8'
)
db.query(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)
Loading…
Cancel
Save