环境介绍
2016-07-2513:32:26
name | value | comment |
OS | win10 | 操作系统 |
python | python3.4 | python主程序 |
IDE | pycharm: 201.2 | python IDE集成开发环境 |
框架 | django: 1.11 | web开发框架,类似与Struts(JAVA) |
DB | mysql: 5.5 | (在centos 上使用二进制安装,你可以直接安装在win10上面) ----- 一款nc的开源数据库 |
connector | PyMySQL | python connector |
作者一路飘来的坑
这就是自己探索的代价,一个小问题都可能停滞1天,或者2天,或者一周
但是,这就是探索的乐趣所在
- pycharm 无法创建django project,只能创建pure python
- 因为pycharm的community版本没有,需要下载professional版本,要注册码,自己百度搞定
- python死活连接不上mysql ---- django内置了sqlite,无需安装,直接使用,但是生产环境一般还是使用mysql,所以这个问题必须解决
- 需要再windows上下载一个DBdriver,我的理解就是一个客户端去驱动连接数据库,python不能直接连接,毕竟db认sql语言,不认识python对吧
- 看介绍:可以安装mysqlclient,connector/python,其实都有问题,因为python3.4太新了(20160725),使用pymysql代替
软件下载
- python: python3.4 www.python.org 这个如果都找不到就不要学python了
- pycharm: 2016.2 http://www.jetbrains.com/pycharm/download/#section=windows 这个注意,请下载 professional 版本
- django: 1.11 https://www.djangoproject.com/download/ 可以源码安装,也可以pip 安装
- mysql: 5.5(在centos 上使用二进制安装,你可以直接安装在win10上面)
- connector: PyMySQL git clone https://github.com/PyMySQL/PyMySQL 如果不熟悉git,可以直接打开后面的网址在网页端下载
软件安装
python
下一步,下一步,一下到底,安装位置作者放在了 C:\Python34
pytharm
下一步,下一步,一下到底
django
方式1 将源代码解压,放到C盘下面吧-----win+r-----cmd---cd c:\dj ---- python setup.py
方式2 ---win+r-----cmd-----pip install django=1.9.2 建议安装这个版本(20160725)
mysql5.5
方式1 下载windows版本的installer ,一下到底
方式2 使用centos6.5,然后下载bin版本的安装(作者采用的方式)
PyMySQL
安装方式和django差不多,进入windows的cmd界面,cd到软件解压目录,然后 python setup.py install
django和pymysql都会安装下面的目录
C:\Python34\Lib\site-packages
创建工程
..1 new---new project
建立好的工程目录类似这个样子
这里可以再多建立几个APP
到现在为止基本的矿机已经完成了,恭喜我自己
..2 让django跑起来
点击工具栏的run
然后在本地打开浏览器输入: http://127.0.0.1:8000/admin
没错,你就成功了,这个系统已经跑起来了,并且你看见了django非常强大的自动生成的一个后台管理界面
..3 让django连接上数据库mysql
..3.1 常见数据库的model
class UserInfo(models.Model):
name = models.CharField(max_length=32)
email = models.CharField(max_length=32)
comment = models.CharField(max_length=32)
age = models.IntegerField()
password = models.CharField(max_length=32,default="") # def __str__(self):
# s = {"id": self.id, "name": self.name, "email": self.email}
# return s
def __str__(self):
return self.name
projectname/appname/models.py
..3.2 配置数据库连接
/projectname/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_db',
'USER': 'root',
'PASSWORD': '',
'HOST': '192.168.202.104',
'PORT': '',
}
}
..3.3 初始化安装你的app
注意后面一定要有逗号,app01 and app02 就是作者自己建立的两个app, 我使用app02,稍后你可以看见设置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
'app02',
]
..3.4 在数据库中建表
manage.py这个时候可以登场了
使用pycharm提供的terminal
python manage.py makemigrations
python manage.py migrate
如果一切正常,你已经在数据库中建表格了,如果有意外,你可以在数据库中先建好db,然后使用这两条命令插入表
..3.5 编写代码对数据库进行增删改查,使用ORM
..3.5.1
"""first_django_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^info/', views.info),
url(r'^home/(\d+)(.*)', views.handle_args),
url(r'^home/', views.home),
url(r'^app01/', include("app01.urls")),
url(r'^app02/', include("app02.urls")), ]
全局的路由系统
"""first_django_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from app02 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^info/', views.info),
url(r'^home/(\d+)(.*)', views.handle_args),
url(r'^home/', views.home),
url(r'^db/add', views.db_add),
url(r'^db/del', views.db_del),
url(r'^db/update', views.db_update),
url(r'^db/select', views.db_select),
url(r'^db/login', views.db_login), ]
/projectname/appname/usrs.py
url会把一个url的请求给到一个view的方法里面
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse, redirect
from app02 import models
from first_django_project import settings def home(request):
return HttpResponse("app02.home") def handle_args(args):
pass def info(request):
pass def db_add(request):
one_user = {"name":"dujuan1", "email":"dujuan.foxmail.com", "comment":"this is comment", "age":23}
models.UserInfo.objects.create(**one_user)
return HttpResponse("add ok") def db_del(request):
models.UserInfo.objects.filter(name="dujuan1").delete()
return HttpResponse("del ok") def db_update(request):
models.UserInfo.objects.filter(name="dujuan1").update(age=25)
return HttpResponse("update ok") def db_select(request):
# ret = models.UserInfo(models.UserInfo.objects.all().first())
# return HttpResponse(ret.name + "---" + ret.email + "-----" + ret.comment + "-----" + ret.age + "----" + "select ok")
#add data to databas first
if request.method == "POST":
submit_data = request.POST
print(submit_data,type(submit_data))
models.UserInfo.objects.create(name = submit_data["name"],
email = submit_data["email"],
comment = submit_data["comment"],
age = submit_data["age"]
)
print("insert into ok")
ret_list = models.UserInfo.objects.all()
# 探测是否获得了数据
for line in ret_list:
print(line.name)
print("select ing ... ...")
myrender = render(request, settings.BASE_DIR + "\\templates\\db_select.html", {"li": ret_list})
return HttpResponse(myrender) def db_login(request):
# login_page_fp = open(settings.BASE_DIR + "\\templates\\app02_login.html", "r", encoding="utf-8")
# login_page_str = str(login_page_fp)
# login_page_fp.close()
if request.method == "POST":
print("-----li------request.method == post")
submit_data = request.POST
submit_data_name = submit_data["name"]
submit_data_email = submit_data["email"]
query_data = models.UserInfo.objects.filter(name=submit_data_name)
# print(query_data,type(query_data))
for item in query_data:
print(item,type(item))
print(item.name)
print(item.email)
cur_email = item.email
if cur_email == submit_data_email:
print("----li----authentication success")
data_list = models.UserInfo.objects.all()
ret_render = render(request, settings.BASE_DIR + "\\templates\\db_select.html", {"li": data_list})
return HttpResponse(ret_render) ret_render = render(request, settings.BASE_DIR + "\\templates\\app02_login.html", context=None)
return HttpResponse(ret_render)
/projectname/appnaem/views.py
views会去models里面去取数据
from django.db import models # Create your models here. class UserInfo(models.Model):
name = models.CharField(max_length=32)
email = models.CharField(max_length=32)
comment = models.CharField(max_length=32)
age = models.IntegerField()
password = models.CharField(max_length=32,default="") # def __str__(self):
# s = {"id": self.id, "name": self.name, "email": self.email}
# return s
def __str__(self):
return self.name class Reporter(models.Model):
name = models.CharField(max_length=32) def __str__(self):
return self.name class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=32)
content = models.TextField()
reporter = models.ForeignKey(Reporter) def __str__(self):
return self.headline
/projectname/appname/models.py
views 还回去templates里面那html样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user info</title>
</head>
<body>
<center>
<table border="">
<thead>
<tr>
<td>name</td>
<td>email</td>
<td>comment</td>
<td>age</td>
</tr>
</thead>
<tbody>
{% for line in li %}
<tr>
<td>{{ line.name }}</td>
<td>{{ line.email }}</td>
<td>{{ line.comment }}</td>
<td>{{ line.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<hr style="height:3px;border:none;border-top:3px double red;" />
<form action="/app02/db/select" method="post">
<table>
<thead>
<tr>
<td>name</td>
<td>value</td>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td><input type="text" name="name" value=""></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email" value=""></td>
</tr>
<tr>
<td>comment</td>
<td><input type="text" name="comment" value=""></td>
</tr>
<tr>
<td>age</td>
<td><input type="text" name="age" value=""></td>
</tr>
<tr>
<td><input type="submit" name="add" value="add"></td>
</tr>
</tbody>
</table>
</form>
</center>
</body>
</html>
/templates/db_select.html
好了,现在运行吧
在浏览器里面输入
http://127.0.0.1:8000/app02/db/select
后台查出来的数据也是这个
特别感谢
http://www.maiziedu.com/article/8579/ ----- 让我知道了PyMySQL
http://python.usyiyi.cn/django/intro/overview.html ---- dango1.8的中文文档,作者英语不是很好,中英文结合看吧
如果有疑问,可以联系作者