• python 培训之Django


      1.Install   

    sudo apt-get install python-pip
    sudo pip install django==1.8

     2. Create Project

    django-admin startproject projname

    3. Create App

    cd prjname
    python manage.py startapp appname

    4. Center URL&&setting

    Control center in projname/projname/
    ##url config
    Url Pattern setting
    url(r^$,include('tcmwebapp.urls')),
    url(r'^tcmwebapp',include('tcmwebapp.urls')),
    ## static url setting
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

    ## setting config
    INSTALL APP( appname )

    5. app urls&&view,

    ## url config
    cd appname/
    touch urls.py
    url(r'xxx',views.fucname,name=XXX)
    ### views.py
    def fucname():
          return HttpResponse("helloworld")
    cd projname/
    python manage.py runserver 9080
    (tip:0.0.0.0:9080)
    chrome localhost:8090
    ### helloworld

    6. Global Config

    cd projname/
    mkdir static
    mkdir templates
    cd appname/
    mkdir static/appname
    mkdir templates/appname

    7. static&templates&setting AutoTool: djangobower

      7.1 Install.

    sudo apt-get install python-software-properties
    sudo apt-get install node
    sudo apt-get install nodejs
    sudo apt-get install npm
    sudo apt-get install git
    curl -SL http://deb
    .nodesource.com/setup_6.x | sudo -E bash -
    sudo apt-get install nodejs-legacy sudo npm install -g bower sudo pip install django-bower

    7.2 Config 

    http://django-bower.readthedocs.io/en/latest/index.html 
    import os
    
    PROJECT_ROOT = os.path.abspath(
        os.path.join(os.path.dirname(__file__), ".."),
    )
    
    DEBUG = True
    TEMPLATE_DEBUG = DEBUG
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'db',
            'USER': '',
            'PASSWORD': '',
            'HOST': '',
            'PORT': '',
        }
    }
    
    STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
    
    STATIC_URL = '/static/'
    
    BOWER_COMPONENTS_ROOT = os.path.join(PROJECT_ROOT, 'components')
    
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'djangobower.finders.BowerFinder',
    )
    
    SECRET_KEY = 'g^i##va1ewa5d-rw-mevzvx2^udt63@!xu$-&di^19t)5rbm!5'
    
    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )
    
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    )
    
    ROOT_URLCONF = 'example.urls'
    
    WSGI_APPLICATION = 'example.wsgi.application'
    
    TEMPLATE_DIRS = (
        os.path.join(PROJECT_ROOT, 'templates'),
    )
    
    INSTALLED_APPS = (
        'django.contrib.staticfiles',
        'djangobower',
    )
    
    BOWER_INSTALLED_APPS = (
        'jquery',
        'underscore',
    )

    7.2 Use

    python manage.py bower_install 
    python manage.py collectstatic
    Change projname center UrlConfig
    urlpattern += (settings.STATIC_URL,name=settings.STATIC_Document)
    urlpattern +=(settings.MEDIA_URL,name=settings.MEDIA_Document)

    8. Design Web Templates

    8.1 View distrubution 

      

    python manage.py makemigrations
    python manage.py migrate
    ### update database 

    8.2 create html 

      8.2.1 base.html 

    projectname/templates/base.html
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE    =edge">
            <meta name="viewport" content = "width=device-width,initial-scale=1">
            <title>
            {% block title %}WebNet{% endblock %} 
            </title>
            {% load staticfiles %}
            <link rel="stylesheet" href={% static 'bootstrap/dist/css/bootstrap.css' %}>
            <script src={% static 'jquery/dist/jquery.min.js' %}></script>
            <script src={% static 'bootstrap/dist/js/bootstrap.min.js' %}></script>
            {% block head %}
            {% endblock %}
        </head>
        <body>
        {% block body %}
        {% endblock %}
        <div class="scripts">
            {% block scripts %}
            {% endblock %}
        </div>
        </body>
    </html>

      8.2.3 user_base.html

    {% extends "base.html" %}
    {% load staticfiles %}
        {% block head %}
    <!--     <link rel="stylesheet" href={% static 'usercenter/css/style.css' %}>
     -->    {% endblock %}
    {% block scripts %}  
    {% endblock %}

    8.3.4 web html 

    {% extends "netapp/base_netapp.html" %}
    {% block body %}
    <link href="/static/netapp/css/search.css" rel="stylesheet">
    
    <section class="content">
        <div class="container-fluid">
            <div class="form">
                <div class="form-title">心脏毒性网络</div>
                <div class="form-body">
                    <form  class="navbar-form" action="/netapp/search" method="post" role="search"> {% csrf_token %}
                        <table>
                            <input type="text" class="form-control" name="chem_name" size="60" maxlength="60" placeholder="Chemical Name">
                            <button type="submit" class="btn btn-danger navbar-btn">Submit</button>
                        </table>
                    </form>
                </div>
            </div>
        </div>
    </section>
    {% endblock %}
    {% block scripts %}
    <!-- <script src = "/static/usercenter/js/userApp.js"></script> -->
    {% endblock %}

    8.3.5 css add 

    .form{
        margin-top: 150px;
        margin-right: 10px;
        margin-left: 10px;
        text-align: center;
    }
    
    .form-title{
      font-weight:bold;
      font-family:arial,verdana,sans-serif;
      font-size:18px;
    }

    9. Design View

    from django.shortcuts import render
    from django.http import HttpResponse
    from tasks import chem_gene_query
    # Create your views here.
    def index(request):
        return render(request,"netapp/index.html")
    
    def search(request):
        if request.method == "POST":
            message = request.POST["chem_name"]
            result = chem_gene_query(message)
            return render(request,"netapp/result.html",{"result":result})
        return render(request,"netapp/index.html")

    10. add scripts in project 

    #!/usr/bin/env/python
    # -*- coding:UTF-8 -*-
    from __future__ import print_function
    import MySQLdb
    import sys
    
    
    def mysql_connect():
        try:
            conn = MySQLdb.connect(host="localhost",user="tcd_net",
                passwd='tcd_net',db='ctd_net',port=3306,charset='utf8')
            cur = conn.cursor()
            return conn,cur
        except MySQLdb.Error,e:
            print(e.args)
            sys.exit(1)
    
    def query_db(conn,cursor,command):
        try:
            cursor.execute(command)
            conn.commit()
            results = cursor.fetchall()
            return results
        except MySQLdb.Error,e:
            print(e.args)
            sys.exit(1)
    
    def chem_gene_query(chem):
        conn,cur = mysql_connect()
        query_command = """select chemicalName,chemicalID,casId,
                        genesymbol,geneid,geneforms,organism,organismid,interaction,
                        interactionActions,pubmedid from chem_gene where chemicalName = "%s";"""%chem
        chem_gene_result = query_db(conn,cur,query_command)
        result = []
        keys = ["chemicalName","chemicalID","casId","genesymbol",
                "geneid","geneforms","organism","organismid",
                "interaction","interactionActions","pubmedid"]
        for res in chem_gene_result:
            out = {}
            for i in range(len(res)):
                out[keys[i]] = res[i]
            if out:
                result.append(out)
        return result

    11. Design results Display

    {% extends "netapp/base_netapp.html" %}
    {% block body %}
    <link href="/static/netapp/css/search.css" rel="stylesheet">
    
    <section class="content">
        <div class="container-fluid">
             <table class="table table-bordered table-condensed">
                   <caption>SearchResults</caption>
                   <thead>
                <tr>
                 <th>chemicalName</th>
                 <th>genesymbol</th>
                 <th>interactionActions</th>
                 <th>pubmedid</th>
                </tr>
                   </thead>
                   {% for i in result %}
                   <tbody>
                    <tr>
                     <td>{{ i.chemicalName }}</td>
                     <td>{{ i.genesymbol }}</td>
                     <td>{{ i.interactionActions }}</td>
                     <td>{{ i.pubmedid }}</td>
                    </tr>
                   </tbody>
                   {% endfor %}
            </table>
         </div>
    </section>
    {% endblock %}
    {% block scripts %}
    <!-- <script src = "/static/usercenter/js/userApp.js"></script> -->
    {% endblock %}
  • 相关阅读:
    eclipse
    ORA00904:标识符无效,preparedstatement
    mysql 创建用户
    web 默认servlet
    https tomat
    gzip
    sftp 上传文件
    jquery dwrutil confilit
    xmlbeans读写xml文件
    敏捷开发“松结对编程”实践大型团队篇
  • 原文地址:https://www.cnblogs.com/xiaojikuaipao/p/5712681.html
Copyright © 2020-2023  润新知