windows下apache+django

安装django1.10.2
python -m pip install django


修改环境变量PATH
d:\python36\Script;


查看版本号
python -m django --version




检查是否安装成功,cmd下运行
C:\Users\Administrator>python -m django


Type '__main__.py help <subcommand>' for help on a specific subcommand.


Available subcommands:


[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata




安装pycharm用于开发python程序的ide
http://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows
----------------------------------------------------------------------------------
新建django项目


D:\workspace_python\mysite


项目的工程目录如下:
mysite/
mysite/
__init__.py
settings.py
urls.py
wsgi.py
templates
manage.py
------------------------------------
创建app(子模块)
在terminal控制台输入:
python manage.py startapp jkx
自动创建jkx文件夹
-------------------------------------
编写路由urls.py
from django.conf.urls import url
from django.contrib import admin
from jkx import views


urlpatterns = [
    #admin后台路由
    #url(r'^admin/', admin.site.urls),
    #添加路由
    url(r'index/',views.index)
]


----------------------------------------------
编写业务处理逻辑jkx/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse




# Create your views here.
def index(request):
    return HttpResponse('Hello word')


-------------------------------------------------
运行web服务
#在不影响其他模块的情况下创建表结构
python manage.py migrate
#检查语法错误
python manage.py validate
#启动服务器
python manage.py runserver


检查运行结果:
http://localhost:8000/index/


------------------------------------------------------------------
返回html
在templates中添加index.html页面,添加如下内容:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>tese</title>
</head>
    <h1 style="background-color: antiquewhite;color: black">hello world</h1>
</html>




修改view.py
from django.shortcuts import render
from django.shortcuts import HttpResponse




# Create your views here.
def index(request):
    # return HttpResponse('Hello word')
    return render(request, 'index.html')
-----------------------------------------------------------------


添加静态文件
在mysite下新建static目录
其他插件也可以放到该目录下
js
imgs
css
plugins


需要在settings.py文件,配置新添加的静态文件


STATIC_URL = '/static/'
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
)






页面中引用js文件
<script src="/static/js/jquery-3.1.1.js"></script>


------------------------------------------------
接收用户发送数据
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>tese</title>
    <script src="/static/js/jquery-3.1.1.js"></script>
</head>
    <h1 style="background-color: antiquewhite;color: black">hello world</h1>
    <h1>用户输入</h1>
    <form action="/index/" method="post">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <input type="submit" value="提交">
    </form>
</html>


修改views.py添加如下内容:
from django.shortcuts import render
from django.shortcuts import HttpResponse




# Create your views here.
def index(request):
    # return HttpResponse('Hello word')
    if request.method=='POST':
        #用户名
        username=request.POST.get('username',None)
        #密码
        password=request.POST.get('password',None)
        print(username,password)
    return render(request, 'index.html')


修改settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #注释掉该行(该行作用是禁止跨站访问请求)
   # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


重启web服务
python manage.py runserver


--------------------------------------------------------------------
返回动态页面


修改view.py文件
from django.shortcuts import render
from django.shortcuts import HttpResponse




# Create your views here.
def index(request):
    # return HttpResponse('Hello word')
    #模拟用户信息列表
    user_list=[
        {'name':'retacn','pwd':'123'},
        {'name':'yue','pwd':'456'},
        {'name':'岳振华','pwd':'123456'},
    ]


    if request.method=='POST':
        #用户名
        username=request.POST.get('username',None)
        #密码
        password=request.POST.get('password',None)
        #print(username,password)
        temp={'name':username,'pwd':password}
        #添加到用户列表
        user_list.append(temp);
    #返回给客户端的用户列表
    return render(request, 'index.html',{'data':user_list})




再修改index.html页面
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>tese</title>
    <script src="/static/js/jquery-3.1.1.js"></script>
</head>
    <h1 style="background-color: antiquewhite;color: black">hello world</h1>
    <h1>Enter User</h1>
    <form action="/index/" method="post">
        UserName:<input type="text" name="username"/><br/>
        Password:<input type="password" name="password"/><br/>
        <input type="submit" value="提交">
    </form>
    <hr>
    <h1>User List</h1>
    <table>
        <thead>
            <th>UserName</th>
            <th>Password</th>
        </thead>
        <tbody>
            {% for user in data %}
                <tr>
                    <td>{{ user.name }}</td>
                    <td>{{ user.pwd }}</td>
                </tr>
            {% endfor %}
        </tbody>


    </table>
</html>


------------------------------------------------------------------------------------
使用数据库
在settings.py中注册app 


DATABASES = {
    'default': {
        #sqlite
       # 'ENGINE': 'django.db.backends.sqlite3',
       # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),


        #mysql
        'ENGINE':'django.db.backends.mysql',
        'NAME':'jkx',
        'USER':'root',
        'PASSWORD':'123456',
        'HOST':'',
        'PORT':'3306',
    }
}


创建数据库和表
数据库名:jkx
表名:jkxs
     user


修改models.py,添加如下内容:
from django.db import models


# Create your models here.
'''
用户信息
'''
class UserInfo(models.Model):
    #id
    id=models.IntegerField(primary_key=True,db_column='id',blank=False)
    #用户名
    name=models.CharField(max_length=20,db_column='name',blank=False)
    #密码
    pwd=models.CharField(max_length=20,db_column='pwd',blank=False)
    #邮箱
    email=models.CharField(max_length=30,db_column='email',blank=False)
    #电话
    phone=models.CharField(max_length=20,db_column='phone',blank=False)
    #备注
    remark=models.CharField(max_length=100,db_column='remark',blank=True)



使用命令来创建数据库的表
python manage.py makemigrations
python manage.py migrate




------------------ 有问题---------------------------
安装MySQL-python
python -m pip install MySQL-python


也可以下载安装包,手动安装
python setup.py install
报如下错误:
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file 


or directory  


解决办法:


安装mysql connector
下载地址http://dev.mysql.com/downloads/file/?id=378015


需要安装vs2015
序列号为:
HM6NR-QXX7C-DFW2Y-8B82K-WTYJV


修改views.py


-------------------------------------------------------
使用pymysql替换mysqldb
修改根目录下的__init__.py,添加如下内容:
#pymysql代替MySQLdb
import pymysql
pymysql.install_as_MySQLdb()


重新执行
python manage.py makemigrations
可以在migrations中看到多了一个0001_initial.py文件
python manage.py migrate


时间需要修改setting.py
TIME_ZONE = 'Asia/Shanghai'




=======================================================
windows下apaceh服务器的安装:
下载地址:
http://archive.apache.org/dist/httpd/binaries/win32/
添加环境变量
path=apache解压目录




报错:
ServerRoot must be a valid directory


解决方法修改 D:\tools\service\Apache24\conf目录下的httpd.conf
Define SRVROOT D:/tools/service/Apache24


cmd下运行httpd报错,错误信息如下:
(OS 10048)通常每个套接字地址(协议/网络地址/端口)只允许使用一次。  : AH00072: make_sock: 


could not bind to address [::]:443
(OS 10048)通常每个套接字地址(协议/网络地址/端口)只允许使用一次。  : AH00072: make_sock: 


could not bind to address 0.0.0.0:443
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs


查看端口占用情况
netstat -ano
查看http服务状态
netsh http show servicestate


由于安装虚拟机,占用433端口
打开虚拟机菜单 编辑→首选项(Edit–> Preferences),修改端口号为444


修改 D:\tools\service\Apache24\conf目录下的httpd.conf
Listen 127.0.0.1:80

安装apache服务
httpd.exe -k install -n apache2.4


启动apach服务
http -k start 


查看运行情况
http://192.168.1.107/

-------------------------------------------------------------------------

apache集成django
注:chmod u+x mysite 
   wsgi.py要可755的权限


其中apache为新源加目录
mkdir apache
cd apache
gedit __init__.py
__init__.py为空文件,告诉python该目录当成包来结待


gedit override.py,添加如下内容:
#override.py
from jkx.settings import *
DEBUG = True
#ALLOWED_HOSTS=['www.***.com','***.com']


gedit wsgi.py,添加如下内容:
#wsgi.py
import os, sys
from django.core.wsgi import get_wsgi_application


# Calculate the path based on the location of the WSGI script.
apache_configuration= os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace)
sys.path.append(project)


# Add the path to 3rd party django application and to django itself.
sys.path.append('/home/retacn')
os.environ['DJANGO_SETTINGS_MODULE'] = 'jkx.apache.override'
import django.core.handlers.wsgi
#application = django.core.handlers.wsgi.WSGIHandler()
application=get_wsgi_application()


为apache服务器分配该目录的所有权
chown www-data:www-data apache/


修改apache
cd /etc/apache2/sites-available
gedit 000-default.conf
<VirtualHost *:80>
ServerName 192.168.1.105
DocumentRoot /home/retacn/mysite

<Directory '/home/retacn/mysite'>
Require all granted
</Directory>


WSGIScriptAlias / /home/retacn/mysite/jkx/apache/wsgi.py


ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>


apt-get insatll cronolog
修改日志存放位置,对应项目的apache/log目录中
修改配置文件,添加如下内容:


CustomLog "|/usr/bin/cronolog /home/retacn/jkx/jkx/apache/logs/access_%Y%m%d.log" common
ErrorLog "|/usr/bin/cronolog /home/retacn/jkx/jkx/apache/logs/error_%Y%m%d.log" 


-------------------apache多应用集成  有问题--------------------------------------
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.


ServerName 192.168.1.105   
#ServerAdmin webmaster@localhost
#
#DocumentRoot /var/www/html
DocumentRoot /home/retacn/jkx
#http://www.mydomain.com/mypath

<Directory '/home/retacn/jkx'>
Require all granted
</Directory>
WSGIScriptAlias / /home/retacn/jkx/jkx/apache/wsgi.py
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn


#ErrorLog ${APACHE_LOG_DIR}/error.log
#CustomLog ${APACHE_LOG_DIR}/access.log combined


CustomLog "|/usr/bin/cronolog /home/retacn/jkx/jkx/apache/logs/access_%Y%m


%d.log" common
ErrorLog "|/usr/bin/cronolog /home/retacn/jkx/jkx/apache/logs/error_%Y%m%d.log"



# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>


lsof –i:5005


================================================================
mysql创建数据库和表
连接数据库
mysql -h127.0.0.1 -uroot -p
-h主机地址
-u用户名
-p密码


输入用户名和密码:


查看数据库状态
status




数据库操作
show databases;//显示数据库
use 数据库名//使用数据库
greate database 数据库名    //创建数据库


远程连接mysql数据库
1 修改/etc/mysql/my.cnf
bind-address=0.0.0.0


2 修改服务器外部权限
grant all privileges on *.* to 'root'@'%' identified by '888';
flush privileges;
重启服务
/etc/init.d/mysql restart

posted @ 2016-10-19 08:25  retacn_yue  阅读(156)  评论(0编辑  收藏  举报