Linux下如何使用Django创建一个helloworld的web程序

Django是一个由Python写成的Web应用框架。Django的主要目的是简便、快速的开发数据库驱动的网站。它强调代码复用,多个组件可以很方便的以“插件”形式服务于整个框架,Django有许多功能强大的第三方插件,你甚至可以很方便的开发出自己的工具包

1、下载与安装

第一步:Django开发与部署,Linux是最佳选择,在Linux上先安装Anaconda环境,如果你Linux系统没有Anaconda环境,请参考我的博客教程:Linux下安装基于Python3.7的Anaconda环境

第二步:安装,如你的安装速度很慢,可以参考我的博客链接:Linux下pip 安装python包更换为国内源

pip install Django

2、创建一个工程

运行下列命令:

# hello为你的工程名
django-admin startproject  hello

这时你的目录结构会变成这样:

在你的hello目录下新建一个view.py文件,该文件与urls.py文件同级哦

cd hello/
# 编辑文件
vi view.py

在你的view.py文件中添加下列代码:

from django.http import HttpResponse

def index(request):
    return HttpResponse("hello, world")

在你的urls.py文件中添加下列代码:

from django.contrib import admin
from django.urls import path

from . import view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', view.index),
]

运行程序:

# 0.0.0.0代表任意ip可以访问,8000为监听端口
python manage.py runserver 0.0.0.0:8000

3、测试

在你的浏览器中输入:http://ip:8000/index/

如果你是在远程访问,比如阿里云,华为云等,会出现下面的错误:

Invalid HTTP_HOST header: ‘x.x.x.x:8000’. You may need to add ‘x.x.x.x’ to ALLOWED_HOSTS.

解决方法,是因为Django默认限制了远程ip的访问,编辑settings.py,做如下修改,来开放远程ip访问

# ALLOWED_HOSTS = [] 改为
ALLOWED_HOSTS = ['*']

重新运行:

0

5 thoughts on “Linux下如何使用Django创建一个helloworld的web程序

  1. Greetings! I’ve been reading your blog for a while now and finally got the courage to go ahead and give you
    a shout out from Humble Tx! Just wanted to tell you keep up the fantastic job!

    0
  2. Hi, this weekend is nice in support of me, because this time i am reading this wonderful educational article
    here at my house.

    0
  3. This design is wicked! You definitely know how to keep a reader
    entertained. Between your wit and your videos, I was almost moved
    to start my own blog (well, almost…HaHa!) Wonderful job.

    I really loved what you had to say, and more than that, how you presented it.
    Too cool!

    0

Leave a Reply

Your email address will not be published.