Python-Django基础知识
作为Python最流行的web框架,django已经深受广大Pythoner喜爱,本站就是基于django实现的。因此,有必要对django的一些基础知识做一些总结,以引领初学者进入Python的web世界。
1.基础知识
1.1.django命令解析
python manager.py “commands”是django-admin命令的封装,项目上用的更多的还是python manager.py commands格式
[auth]changepassword:修改admin密码createsuperuser:创建超级管理员
[django]check:检查项目状态,包括:数据库模型状态startapp:创建新的应用runserver:运行服务makemigrations:告诉django,对于模型做了一些更改,并且将这些更改存储为迁移文件,其实是生成一些python的数据库管理脚本migrate:运行迁移文件,并自动管理数据库,其实就是运行数据库管理脚本,创建数据库,表等dumpdata:导出数据到json文件loaddata:从json文件导入数据shell:启动django的shell,设置了相关的环境变量,使用起来很方便,其实本质上,还是个python的shell
1.2安装环境
首先需要有Python dev环境
安装pip,easy_install工具
pip install django #安装最新版本的Django,也可以自己下载django源码安装
如果需要运行多个版本的Djanjo,可以安装虚拟环境:pip install virtualenv virtualenvwrapper
1.3创建项目和应用
django-admin startproject project_namecd project_namepython manager.py startapp app_name
把app名字加入到工程配置目录下的settings.py中
1.4启动项目
python manager.py runserver ip_addr:port
1.5浏览器访问
http://ip_addr:port/
这是开发模式下的访问方式,在生产环境,需要部署到apache或nginx。
1.6.工程目录详解
bogon:zqxt_tmpl david$ tree.├── db.sqlite3 #数据库文件├── learn #app名称│ ├── __init__.py #模块初始化文件│ ├── __init__.pyc│ ├── admin.py #注册module│ ├── admin.pyc│ ├── apps.py #app配置│ ├── migrations #数据库迁移│ │ ├── __init__.py│ │ └── __init__.pyc│ ├── models.py #数据库模块,读写数据库使用│ ├── models.pyc│ ├── templates #html模板目录│ │ └── home.html #html文件│ ├── tests.py #测试代码│ ├── views.py #业务逻辑处理,处理http请求│ └── views.pyc├── manage.py #项目管理,内含多个命令,可以创建app,启动项目,迁移数据库等等└── zqxt_tmpl #项目目录 ├── __init__.py #项目文件 ├── __init__.pyc ├── settings.py #项目设置 ├── settings.pyc ├── urls.py #项目URL处理,网址入口 ├── urls.pyc ├── wsgi.py #项目发布后,web服务器使用 └── wsgi.pyc此外,还有form.py,完成表单处理工作
2.将django项目部署到apache
2.1将django工程拷贝到/var/www/(也可以是别的目录)
以yue工程为例:
cp -r yue /var/www/收集静态文件,在/var/www/yue/执行:python manage.py collectstatic
2.2修改Apache2配置文件
1)ports.conf添加listen端口root@abellee:/etc/apache2# cat ports.conf# If you just change the port or add more ports here, you will likely also# have to change the VirtualHost statement in# /etc/apache2/sites-enabled/000-default.confListen 80Listen 8888<IfModule ssl_module>Listen 443</IfModule><IfModule mod_gnutls.c>Listen 443</IfModule>
2)在/etc/apache2/sites-available目录下建立yue.conf文件
root@abellee:/etc/apache2/sites-available# cat yue.conf<VirtualHost *:8888>ErrorLog ${APACHE_LOG_DIR}/error.logCustomLog ${APACHE_LOG_DIR}/access.log combinedWSGIScriptAlias / /var/www/yue/yue/wsgi.pyAlias /static /var/www/yue/collected_static</VirtualHost>
3)在/etc/apache2/sites-enabled目录下建立软链接,重启服务
yue.conf -> ../sites-available/yue.conf重启apache2服务浏览器执行: http://127.0.0.1:8888/
3.FAQ
注意:部署过程中会遇到问题
1.首先,必须保证: python /var/www/yue/yue/wsgi.py 不报错2.如果发现django 403错误,请在yue/setting.py中删除csrf保护机制,直接在setting.py中搜索setting3.需要添加django工程目录到Python的path中wsgi.py文件中添加:import syspaths =["/var/www/yue"]for path in paths:if path not in sys.path:sys.path.append(path)
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。