今天我们来聊聊[pythonwebdjango搭建网站],以下5个是关于pythonwebdjango搭建网站的观点,希望能帮助到您找到想要的,更多相关的资讯继续关注本站。
如何创建一个Django网站
本文贡献者:【夏日冰糖雪梨】 ,解答(pythonwebdjango搭建网站)的问题,如果问题解决,可以关注本站!
最佳回答本文演示如何创建一个简单的 django 网站,使用的 django 版本为1.7。
1. 创建项目
运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :
$ django-admin.py startproject mysite
创建后的项目目录如下:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
说明:
__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。
manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。
settings.py :该 Django 项目的设置或配置。
urls.py:Django项目的URL路由设置。目前,它是空的。
wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI
接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
上面开启了 [Time zone]() 特性,需要安装 pytz:
$ sudo pip install pytz
2. 运行项目
在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial. OK
Applying auth.0001_initial. OK
Applying admin.0001_initial. OK
Applying sessions.0001_initial. OK
然后启动服务:
$ python manage.py runserver
你会看到下面的输出:
Performing system checks.
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at
Quit the server with CONTROL-C.
这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。
你也可以指定启动端口:
$ python manage.py runserver 8080
以及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3. 创建 app
前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。
在项目目录下创建一个 app:
$ python manage.py startapp polls
如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:
polls
├── __init__.py
├── admin.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 6 files
4. 创建模型
每一个 Django Model 都继承自 django.db.models.Model
在 Model 当中每一个属性 attribute 都代表一个 database field
通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句
打开 polls 文件夹下的 models.py 文件。创建两个模型:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:
$ python manage.py makemigrations polls
你会看到下面的输出日志:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
你可以从 polls/migrations/0001_initial.py 查看迁移语句。
运行下面语句,你可以查看迁移的 sql 语句:
$ python manage.py sqlmigrate polls 0001
输出结果:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
你可以运行下面命令,来检查数据库是否有问题:
$ python manage.py check
再次运行下面的命令,来创建新添加的模型:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial. OK
总结一下,当修改一个模型时,需要做以下几个步骤:
修改 models.py 文件
运行 python manage.py makemigrations 创建迁移语句
运行 python manage.py migrate,将模型的改变迁移到数据库中
你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。
创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:
$ python manage.py shell
下面是一些测试:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
[]
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]
打印所有的 Question 时,输出的结果是 [<Question: Question object>],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:
from django.db import models
class Question(models.Model):
# .
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# .
def __str__(self): # __unicode__ on Python 2
return self.choice_text
接下来继续测试:
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up>]
# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up>
# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
.
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up>
# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]
# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up>
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
>>>
上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。
5. 管理 admin
Django有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.
新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:
INSTALLED_APPS = (
'django.contrib.admin', #默认添加后台管理功能
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:
url(r'^admin/', include(admin.site.urls)), #可以使用设置好的url进入网站后台
接下来我们需要创建一个管理用户来登录 admin 后台管理界面:
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
总结
最后,来看项目目录结构:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── polls
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
└── templates
└── admin
└── base_site.htm
通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。
以上就是重庆云诚科技小编解疑贡献者:(夏日冰糖雪梨)分析的关于“如何创建一个Django网站”的问题了,不知是否已经解决你的问题?如果没有,下一篇内容可能是你想要的答案,接下来继续分折下文用户【一个人的精彩】解答的“Python可以开发网站吗?”的一些相关疑问做出分析与解答,如果能找到你的答案,可以关注本站。

Python可以开发网站吗?
体育爱好者提供:【一个人的精彩】 ,解答(pythonwebdjango搭建网站)的问题,如果问题解决,可以关注本站!
最佳回答Python是可以开发网站的,国内的豆瓣就是典型的Python开发的;使用python Django做网页的步骤:
1 、创建一个django项目(使用django-admin.py startproject MyDjangoSite )
2、建立视图
from django.http import HttpResponsedef hello(request): return HttpResponse("第一个简单的python django项目。")
3、修改urls.py
为urlpatterns加上一行: (r‘^hello/$', hello), 这行被称作URLpattern,它是一个Python的元组。元组中第一个元素是模式匹配字符串(正则表达式);第二个元素是那个模式将使用的视图函数。
正则表达式字符串的开头字母“r”。 它告诉Python这是个原始字符串,不需要处理里面的反斜杠(转义字符)。一般在使用正则前加入"r"是一个好的习惯。
4、运行python manage.py runserver
以上就是重庆云诚科技小编解答(一个人的精彩)分析关于“Python可以开发网站吗?”的答案,接下来继续为你详解体育用户(血之狂魔)贡献“如何部署python web程序”的一些相关解答,希望能解决你的问题!
如何部署python web程序
体育爱好者提供:【血之狂魔】 ,解答(pythonwebdjango搭建网站)的问题,如果问题解决,可以关注本站!
最佳回答Python Web 程序的部署方案
综合而言, 高性能的Python web站点部署方式首推 nginx + uwsgi
apache + mod_wsgi 是简单稳定但性能一般的方式
API服务器 可以直接使用tornado或者gevent
mod_python
非常原始的cgi模式部署python已经没有什么好介绍了。对于不太追求性能的管理系统和网站来说,使用 Apache 部署是一个不错的选择。较早的时候,使用 mode_python 部署python的web应用十分流行,在Django 0.96 的时候官方文档甚至推荐这种方式。
它将Python解释器嵌入到Apache server,以提供一个访问Apache server内部的接口。mod_python 在现在看来性能是不佳的,每一个http请求 mod_python 都会由一个进程初始化python解释器、载入代码、执行、然后销毁进程。
mod_wsgi
如果非要用Apache来部署python应用,mod_wsgi是一个更好的选择。WSGI 全称是 Web Server Gateway Interface ,由 PEP-333 定义。 基本上所有的python web框架都实现了wsgi接口,用mod_wsgi 能部署任何实现了wsgi的框架。实际上,不需要任何框架也可以用mod_wsgi 部署python程序。使用mod_wsgi的daemon模式,python程序会常驻内存,不会有很大的初始化和销毁进程方面的开销,所以性能是好于mod_python的。综合来说,使用Apache部署python web程序,推荐使用mod_wsgi的daemon模式。
Fastcgi
先说观点:不建议用fastcgi的方式部署Python web。
前几年由于lighttpd风头正劲和豆瓣的成功案例,fastcgi是一种很流行的部署方式。fastcgi与具体语言无关,也与web服务器无关。是一种通用的部署方式。fastcgi是对于cgi的增强,CGI程序运行在独立的进程中,并对每个Web请求建立一个进程。面对大量请求,进程的大量建立和消亡使操作系统性能大大下降。
与为每个请求创建一个新的进程不同,FastCGI使用持续的进程来处理一连串的请求。这些进程由FastCGI服务器管理,而不是web服务器。 当进来一个请求时,web服务器把环境变量和这个页面请求通过一个socket比如FastCGI进程与web服务器都位于本地)或者一个TCP connection(FastCGI进程在远端的server farm)传递给FastCGI进程。
主流的web服务器,Apache,lighttpd,nginx 都支持fastcgi,在几年前,lighttpd的mod_fcgi模块性能强劲,lighttpd+fastcgi十分流行。无论是python,ruby还是php,都有大量的站点使用这种方式部署。由于nginx的崛起,现在很少有人使用lighttpd了。
fastcgi 并不是专门为python设计,并不是所有的python框架天然的支持fastcgi,通常需要flup这样的容器来配适。flup由python编写,和专门的c实现的wsgi容器比起来性能显得相当不堪。fastcgi的稳定性对于新兴的wsgi容器来说也有差距。无论从哪个方面来看,部署python web程序,fastcgi 都已经是过去式。
uwsgi
前几年nginx还未内置uwsgi模块的时候,部署uwsgi还是一件挺麻烦的事情。随着能够在nginx中直接使用uwsgi模块,uwsgi已经是最可靠,最方便的高性能python web程序的部署方式了。
在1U的四核XEON服务器上,一个简单的wsgi handler甚至能用AB压到8000的qps,这已经是完爆tornado,接近gevent的性能了。 同时,uwsgi的稳定性极好。之前我们有个每天500w-1000w动态请求的站点使用uwsgi部署非常稳定,在一个渣HP 1U 服务器上,基本不用管它。
上面提到的部署方式都是相对于web网站的方式,在移动互联网的时代,我们需要的是高性能的API服务,上面这些都是过时的东西。
tornado
tornado 号称高性能,如果拿他写网站,其实一般般,只不过跟uwsgi加一些简单框架而已。它真正的作用,是用来写API服务器和长连接的服务器。
由于tornado能够直接处理http请求,很多人直接拿他来裸奔直接提供服务。这种方式是不可取的,单线程的tornado只能利用cpu的一个核心,并且一旦阻塞直接就废了。通常情况下,由supervisor启动多个tornado进程,通过nginx进行反向代理负载均衡。nginx 1.14 以后的版本反向代理支持长连接,配合tornado的comet效果很好。
tornado还有一些比较奇葩的用法,比如用来做wsgi容器之类的。
gevent
gevent是一个神器,能做的事情很多。在web方面,处理http请求,用起来其实跟tornado,但是要简陋很多,cookie之类的都没有。用gevent写的一些API服务,部署方式还是类似tornado,用supervisor管理多个守护进程,通过nginx做负载均衡。 同样的它的奇葩用法也和tornado一样,可以当wsgi容器用。
上文就是重庆云诚科技小编解答贡献者:(血之狂魔)贡献的关于“如何部署python web程序”的问题了,不知是否已经解决你的问题?如果没有,下一篇内容可能是你想要的答案,接下来继续描述下文用户【雨碎江南】分享的“python能做网站吗”的一些相关疑问做出分析与解答,如果能找到你的答案,可以关注本站。
python能做网站吗
本文贡献者:【雨碎江南】 ,解答(pythonwebdjango搭建网站)的问题,如果问题解决,可以关注本站!
最佳回答python可以做网站,Python有很多优秀的网站框架,可以非常快速的建一个网站。比如django之类的框架。
Django、TurboGears、Eurasia、UliWeb等:突出的共同特色有:
有内置的 ORM 模块支持数据库的对象化操作;
有内置的事务性功能支持(比如说登录认证);
有高级的模板系统,支持复杂的页面组合,有的甚至有内置的 Ajax 页面动态效果支持。
使用django框架建站的步骤:
1、导入django包
可直接在pycharm下载,或者pip/easy_install
2、设置环境变量
path 添加 C:Python27Libsite-packagesdjangobin;C:Python27Scripts
3、新建一个工程
D:>django-admin.py startproject mysite
4、工程下新建一个app
D:mysite> python manage.py startapp blog
5、初始化admin后台数据库
D:mysite>python manage.py migrate
6、启动服务
D:mysite>python manage.py runserver
更多Python知识请关注Python视频教程栏目。
以上就是重庆云诚科技小编解答(雨碎江南)贡献关于“python能做网站吗”的答案,接下来继续为你详解体育用户(余香ヾ)解答“Django开发网站要多久”的一些相关解答,希望能解决你的问题!
Django开发网站要多久
本文贡献者:【余香ヾ】 ,解答(pythonwebdjango搭建网站)的问题,如果问题解决,可以关注本站!
最佳回答django不难,难在网站的美化和用户体验优化。我目前学django一个月,开发一个视频类网站,算是做了一个demo版本了,各功能可以正常运行,但是遇到以下问题需要解决:
网站美化:css,bootstrap,js等不知道如何和django的表单最大限度融合使用。我目前的感觉是如果使用js,就必须自己在模板中写表单。
功能拓展:django虽说是一个强大的框架,但是还是有很多地方需要自己定制。比如用户登陆系统,django自身比较简单,而第三方的app虽然功能完善,但是其帮助文档一般是2句话说完,对于新手实在门槛过高。
关于[pythonwebdjango搭建网站]的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、pythonwebdjango搭建网站的信息别忘了在本站进行查找喔。
推荐文章:
本文由网上采集发布,不代表我们立场,转载联系作者并注明出处:https://www.cqycseo.com/zixun/6211.html
