python + django + echart 构建中型项目

1. python生产环境, 多层modules 导入问题:

多个modules 如何导入不同级别的包:

在每个modules下新建 __init__.py

import os, sys

dir_mytest = os.path.dirname(os.path.abspath(__file__)) # crontab 跑时 os.getcwd() 只会取到用户的路径....

sys.path.insert(0, dir_mytest+"tmp\\t1")

#sys.path.insert(0,os.getcwd())

在控制目录的执行文件中:

from module import py

如果是三层结构或者更多:

from module.submodule.submodule.py import *

2. django 结构:

->1. 在admin层 urls.py 设置路由:

# 导入app模块的控制层

from app_name import views

urlpatterns = [

#path('admin/', admin.site.urls),

path('index/', views.index)

]

->2. 在app业务处理层 views.py 编写处理逻辑:

#导入HttpResponse模块

from django.shortcuts import HttpResponse

def index(request):

return HttpResponse("hello world")

在此可以进行python的业务编码处理。

->3. 在app业务处理层, settings.py 设置数据库连接:

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'app_name'

]

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql', #此项不变

'NAME': 'mydata', #设置的数据库名称

'USER': 'root', #mysql 的登录用户名

'PASSWORD': '123456', #mysql的登录密码

'HOST': 'localhost', #默认为127.0.0.1

'PORT': '3306', #默认端口:3306

'charset': 'utf8',

}

}

import pymysql

pymysql.install_as_MySQLdb()

conda install mysqlclient=1.3.13

mysqlclient 1.3.3 or newer is required; you have 0.7.11.None

通过查找路径C:\Programs\Python\Python36-32\Lib\site-packages\Django-2.0-py3.6.egg\django\db\backends\mysql\base.py

这个路径里的文件把

if version < (1, 3, 3):

raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)

query = query.decode(errors='replace')

将这段代码注释掉

########### pyecharts ##############################################################

安装pyecharts: pip install pyecharts

script_list 是 Page() 类渲染网页所需要依赖的 echarts js 库,依赖的库的数量取决于所要渲染的图形种类。

echarts js 库的地址,默认的地址为 http://chfw.github.io/jupyter-echarts/echarts

在app_name下, 创建templates目录;

-> 在该目录下:

:创建一个static:存放echarts.js

: 创建一个pyecharts.html:

<head>

<meta charset="utf-8">

<title>Proudly presented by PycCharts</title>

{% for jsfile_name in script_list %}

{% load staticfiles %}

<!-- <script src="{% static '/echarts/{{jsfile_name}}.js' %}"></script> -->

<script src="/static/echarts/{{jsfile_name}}.js"></script>

{% endfor %}

</head>

<body>

<!--|safe 过滤器, 不对字符串进行转义-->

{{myechart|safe}}

</body>

######################## debug ###############################

报错:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737:

打开:

File "E:\software\Anaconda\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html

t = DEBUG_ENGINE.from_string(fh.read())

在331行修改: .open(encoding="utf-8") as fh