zoukankan      html  css  js  c++  java
  • windows10 -- mysql5.5 + python3.4 + django1.11 +pycharm2016.2 + PyMySQL(DB DRIVER) 环境搭建

    环境介绍

    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代替

    软件下载

    1. python: python3.4      www.python.org  这个如果都找不到就不要学python了
    2. pycharm:  2016.2        http://www.jetbrains.com/pycharm/download/#section=windows  这个注意,请下载 professional 版本
    3. django:  1.11              https://www.djangoproject.com/download/      可以源码安装,也可以pip 安装
    4. mysql: 5.5(在centos 上使用二进制安装,你可以直接安装在win10上面)
    5. 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:Python34Libsite-packages

    创建工程

     ..1 new---new project

    建立好的工程目录类似这个样子

    这里可以再多建立几个APP

    到现在为止基本的矿机已经完成了,恭喜我自己

    ..2 让django跑起来

    点击工具栏的run

    然后在本地打开浏览器输入:    http://127.0.0.1:8000/admin

    没错,你就成功了,这个系统已经跑起来了,并且你看见了django非常强大的自动生成的一个后台管理界面

    ..3 让django连接上数据库mysql

    ..3.1 常见数据库的model

     1 class UserInfo(models.Model):
     2     name = models.CharField(max_length=32)
     3     email = models.CharField(max_length=32)
     4     comment = models.CharField(max_length=32)
     5     age = models.IntegerField()
     6     password = models.CharField(max_length=32,default="123456")
     7 
     8     # def __str__(self):
     9     #     s = {"id": self.id, "name": self.name, "email": self.email}
    10     #     return s
    11     def __str__(self):
    12         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': '123456',
            'HOST': '192.168.202.104',
            'PORT': '3306',
        }
    }
    ..3.3 初始化安装你的app
    注意后面一定要有逗号,app01 and app02 就是作者自己建立的两个app, 我使用app02,稍后你可以看见设置
     1 INSTALLED_APPS = [
     2     'django.contrib.admin',
     3     'django.contrib.auth',
     4     'django.contrib.contenttypes',
     5     'django.contrib.sessions',
     6     'django.contrib.messages',
     7     'django.contrib.staticfiles',
     8     'app01',
     9     'app02',
    10 ]

     ..3.4 在数据库中建表

    manage.py这个时候可以登场了

    使用pycharm提供的terminal

    python manage.py makemigrations

    python manage.py migrate

    如果一切正常,你已经在数据库中建表格了,如果有意外,你可以在数据库中先建好db,然后使用这两条命令插入表

    ..3.5 编写代码对数据库进行增删改查,使用ORM

    ..3.5.1 

     1 """first_django_project URL Configuration
     2 
     3 The `urlpatterns` list routes URLs to views. For more information please see:
     4     https://docs.djangoproject.com/en/dev/topics/http/urls/
     5 Examples:
     6 Function views
     7     1. Add an import:  from my_app import views
     8     2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
     9 Class-based views
    10     1. Add an import:  from other_app.views import Home
    11     2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
    12 Including another URLconf
    13     1. Import the include() function: from django.conf.urls import url, include
    14     2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
    15 """
    16 from django.conf.urls import url,include
    17 from django.contrib import admin
    18 from app01 import views
    19 
    20 urlpatterns = [
    21     url(r'^admin/', admin.site.urls),
    22     url(r'^info/', views.info),
    23     url(r'^home/(d+)(.*)', views.handle_args),
    24     url(r'^home/', views.home),
    25     url(r'^app01/', include("app01.urls")),
    26     url(r'^app02/', include("app02.urls")),
    27 
    28 ]
    全局的路由系统
     1 """first_django_project URL Configuration
     2 
     3 The `urlpatterns` list routes URLs to views. For more information please see:
     4     https://docs.djangoproject.com/en/dev/topics/http/urls/
     5 Examples:
     6 Function views
     7     1. Add an import:  from my_app import views
     8     2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
     9 Class-based views
    10     1. Add an import:  from other_app.views import Home
    11     2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
    12 Including another URLconf
    13     1. Import the include() function: from django.conf.urls import url, include
    14     2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
    15 """
    16 from django.conf.urls import url,include
    17 from django.contrib import admin
    18 from app02 import views
    19 
    20 urlpatterns = [
    21     url(r'^admin/', admin.site.urls),
    22     url(r'^info/', views.info),
    23     url(r'^home/(d+)(.*)', views.handle_args),
    24     url(r'^home/', views.home),
    25     url(r'^db/add', views.db_add),
    26     url(r'^db/del', views.db_del),
    27     url(r'^db/update', views.db_update),
    28     url(r'^db/select', views.db_select),
    29     url(r'^db/login', views.db_login),
    30 
    31 ]
    /projectname/appname/usrs.py

    url会把一个url的请求给到一个view的方法里面

     1 from django.shortcuts import render
     2 # Create your views here.
     3 from django.shortcuts import HttpResponse, redirect
     4 from app02 import models
     5 from first_django_project import settings
     6 
     7 
     8 def home(request):
     9     return HttpResponse("app02.home")
    10 
    11 
    12 def handle_args(args):
    13     pass
    14 
    15 
    16 def info(request):
    17     pass
    18 
    19 
    20 def db_add(request):
    21     one_user = {"name":"dujuan1", "email":"dujuan.foxmail.com", "comment":"this is comment", "age":23}
    22     models.UserInfo.objects.create(**one_user)
    23     return HttpResponse("add ok")
    24 
    25 
    26 def db_del(request):
    27     models.UserInfo.objects.filter(name="dujuan1").delete()
    28     return HttpResponse("del ok")
    29 
    30 
    31 def db_update(request):
    32     models.UserInfo.objects.filter(name="dujuan1").update(age=25)
    33     return HttpResponse("update ok")
    34 
    35 
    36 def db_select(request):
    37     # ret = models.UserInfo(models.UserInfo.objects.all().first())
    38     # return HttpResponse(ret.name + "---" + ret.email + "-----" + ret.comment + "-----" + ret.age + "----" + "select ok")
    39     #add data to databas first
    40     if request.method == "POST":
    41         submit_data = request.POST
    42         print(submit_data,type(submit_data))
    43         models.UserInfo.objects.create(name = submit_data["name"],
    44                                        email = submit_data["email"],
    45                                        comment = submit_data["comment"],
    46                                        age = submit_data["age"]
    47                                        )
    48         print("insert into ok")
    49     ret_list = models.UserInfo.objects.all()
    50     # 探测是否获得了数据
    51     for line in ret_list:
    52         print(line.name)
    53     print("select ing ... ...")
    54     myrender = render(request, settings.BASE_DIR + "\templates\db_select.html", {"li": ret_list})
    55     return HttpResponse(myrender)
    56 
    57 def db_login(request):
    58     # login_page_fp = open(settings.BASE_DIR + "\templates\app02_login.html", "r", encoding="utf-8")
    59     # login_page_str = str(login_page_fp)
    60     # login_page_fp.close()
    61     if request.method == "POST":
    62         print("-----li------request.method == post")
    63         submit_data = request.POST
    64         submit_data_name = submit_data["name"]
    65         submit_data_email = submit_data["email"]
    66         query_data = models.UserInfo.objects.filter(name=submit_data_name)
    67         # print(query_data,type(query_data))
    68         for item in query_data:
    69             print(item,type(item))
    70             print(item.name)
    71             print(item.email)
    72             cur_email = item.email
    73             if cur_email == submit_data_email:
    74                 print("----li----authentication success")
    75                 data_list = models.UserInfo.objects.all()
    76                 ret_render = render(request, settings.BASE_DIR + "\templates\db_select.html", {"li": data_list})
    77                 return HttpResponse(ret_render)
    78 
    79     ret_render = render(request, settings.BASE_DIR + "\templates\app02_login.html", context=None)
    80     return HttpResponse(ret_render)
    /projectname/appnaem/views.py

     views会去models里面去取数据

     1 from django.db import models
     2 
     3 # Create your models here.
     4 
     5 
     6 class UserInfo(models.Model):
     7     name = models.CharField(max_length=32)
     8     email = models.CharField(max_length=32)
     9     comment = models.CharField(max_length=32)
    10     age = models.IntegerField()
    11     password = models.CharField(max_length=32,default="123456")
    12 
    13     # def __str__(self):
    14     #     s = {"id": self.id, "name": self.name, "email": self.email}
    15     #     return s
    16     def __str__(self):
    17         return self.name
    18 
    19 
    20 class Reporter(models.Model):
    21     name = models.CharField(max_length=32)
    22 
    23     def __str__(self):
    24         return self.name
    25 
    26 
    27 class Article(models.Model):
    28     pub_date = models.DateField()
    29     headline = models.CharField(max_length=32)
    30     content = models.TextField()
    31     reporter = models.ForeignKey(Reporter)
    32 
    33     def __str__(self):
    34         return self.headline
    /projectname/appname/models.py

    views 还回去templates里面那html样式

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>user info</title>
     6 </head>
     7 <body>
     8 <center>
     9     <table border="1">
    10         <thead>
    11             <tr>
    12                 <td>name</td>
    13                 <td>email</td>
    14                 <td>comment</td>
    15                 <td>age</td>
    16             </tr>
    17         </thead>
    18         <tbody>
    19             {% for line in li %}
    20             <tr>
    21                 <td>{{ line.name }}</td>
    22                 <td>{{ line.email }}</td>
    23                 <td>{{ line.comment }}</td>
    24                 <td>{{ line.age }}</td>
    25             </tr>
    26             {% endfor %}
    27         </tbody>
    28     </table>
    29     <br>
    30     <hr style="height:3px;border:none;border-top:3px double red;" />
    31     <form action="/app02/db/select" method="post">
    32         <table>
    33             <thead>
    34                 <tr>
    35                     <td>name</td>
    36                     <td>value</td>
    37                 </tr>
    38             </thead>
    39             <tbody>
    40                 <tr>
    41                     <td>name</td>
    42                     <td><input type="text" name="name" value=""></td>
    43                 </tr>
    44                 <tr>
    45                     <td>email</td>
    46                     <td><input type="text" name="email" value=""></td>
    47                 </tr>
    48                 <tr>
    49                     <td>comment</td>
    50                     <td><input type="text" name="comment" value=""></td>
    51                 </tr>
    52                 <tr>
    53                     <td>age</td>
    54                     <td><input type="text" name="age" value=""></td>
    55                 </tr>
    56                 <tr>
    57                     <td><input type="submit" name="add" value="add"></td>
    58                 </tr>
    59             </tbody>
    60         </table>
    61     </form>
    62 </center>
    63 </body>
    64 </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的中文文档,作者英语不是很好,中英文结合看吧

    如果有疑问,可以联系作者

    yangliw3@foxmail.com

  • 相关阅读:
    oracle 之 while循环月份
    oracle 之 for循环表
    基本类型与字符串之间的转换
    java的数据类型和mysql的数据类型和Oracle数据类型
    EasyPoi导入数据后,导出发生错误的数据报[object Object]
    mysql查询表名是否存在和oracle查询表名是否存在
    mysql服务相关命令
    vue:按钮后面加一个下拉箭头
    js删除对象中的属性使用delete
    为什么在前端存入的日期,到后台却多了8个小时?而且前端显示的又是很丑的时间戳
  • 原文地址:https://www.cnblogs.com/fepapa/p/5703169.html
Copyright © 2011-2022 走看看