Python实战:个人博客网站搭建

编程环境

  • Google浏览器
  • 致网OpenLAB网络实验平台

安装Django框架

  • 1、打开python控制台,检查有无安装django框架
1
import django
  • 2、通过国内服务器加速安装Django框架
1
pip install django -i https://pypi.douban.com/simple/
  • 3、进入python环境
1
python
  • 4、导入django
1
import django
  • 5、查看django版本信息
1
django.VERSION
  • 6、退出python环境
1
exit()

创建Django工程项目

1
django-admin startproject webDemo

创建Django的blog app

1
django-admin startapp zyb_blog

配置settings.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ALLOWED_HOSTS = ['*']
//允许所有ip的请求

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'zyb_blog',
//添加我的blog app
]

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',
]

启动Django工程

1
python manage.py runserver 0.0.0.0:8090

新建一条你的url

  • 1、修改urls.py文件,新建url
1
2
3
4
5
6
7
8
from django.conf.urls import url
from django.contrib import admin
from zyb_blog import views //add

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^zyb_blog/',views.zyb_blog) //add
]
  • 2、修改views.py文件,创建对应处理函数
1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.
def zyb_blog(request):

context = {}
return render(request,'zyb_blog.html',context)
  • 3、生成外部访问url
1
http://58.213.119.26:18080/api/v1/namespaces/web-ide/services/theia-ide-abb35e498637:web-8090/proxy/zyb_blog/

创建templates文件夹

  • 1、在你的博客文件夹zyb_blog下新建templates文件夹

  • 2、在templates文件夹下创建zyb_blog.html文件并添加内容

1
2
3
4
5
6
7
8
<html>
    <head>

    </head>
    <body>
        <p>hello</p>
    </body>
<html>

完善你的博客主页

  • 1、新建对应所需文件夹

在你的博客目录下新建static文件夹,并在static文件夹下新建img文件夹js文件夹

  • 2、添加或上传需要的文件到对应文件夹

上传一个图片head.jpgimg文件夹,上传jquery-3.3.1.min.jsjs文件夹

  • 3、修改主页文件zyb_blog.html的标签,新增inputtextarea标签
1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
    <head>

    </head>
    <body>
        <div>
        <p>hello</p>
        <input id="title" type="text" placeholder="请输入标题"><br>
        <textarea id="context" cols="20" rows="20" placeholder="请输入内容"></textarea><br>
        <button id="submit_btn">发布内容</button>
        </div>
    </body>
<html>
  • 4、新建博客主页中相关控件所需的js文件zyb_blog.js,并编辑内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//监听button按钮
$('#submit_btn').on('click',function(){

    var title = $('#title').val();
    var context = $('#context').val();
    var post_data = {"title":title,"context":context};
//获取input输入
    console.log('HELLO zyb');//测试监听按钮是否正常
    console.log(title);
    console.log(context);
//新建ajax请求
    $.ajax({
        type: "POST",
        url: "zyb_blog/",
        data: post_data,
        success: function(data){
            console.log('return&nbspsuccess');
        }

    });

});
  • 5、修改views.py文件,修改view函数,接受post请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.
def zyb_blog(request):

if request.method == "GET":
context = {}
return render(request,'zyb_blog.html',context)
else:
title = request.POST.get("title")
context = request.POST.get("context")
print(title)
print(context)
context = {"result": "success"}
return JsonResponse(context)
  • 6、修改zyb_blog.html的文件,应用个性化zyb_blog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{% load static %}

<html>
    <head>

    </head>
    <body>
        <div>
        <p>hello</p>
        <input id="title" type="text" placeholder="请输入标题"><br>
        <textarea id="context" cols="20" rows="20" placeholder="请输入内容"></textarea><br>
        <button id="submit_btn">发布内容</button>
        </div>
    </body>
<html>

<script src="/static/js/jquery-3.3.1.min.js"></script>
<script src="/static/js/zyb_blog.js"></script>
  • 7、修改主页文件zyb_blog.html,新建博客主页头部head,使用<img>标签引用图片
1
<img src="/static/img/head.jpg">
  • 8、启动数据库,新建数据库webDemo
1
2
3
4
5
6
7
8
9
10
//启动数据库
service mysql start
//链接数据库
mysql -u root -popenlab
//查看数据库
show databases;
//创建数据库webDemo
create database webDemo default charset utf8;
//进入数据库
use webDemo;
  • 9、配置Django工程使用已创建的数据库:修改settings.py文件连接数据库
1
2
3
4
5
6
7
8
9
10
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "webDemo",
'USER': "root",
'PASSWORD':"openlab",
'HOST':'127.0.0.1',
'PORT':'3306'
}
}
  • 10、安装python操作mysql数据库的包,指定国内源加速下载
1
root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# pip install mysqlclient -i https://pypi.douban.com/simple/
  • 11、修改models.py文件,在已有数据库中的创建表,保存所需数据(无需再进入MySQL中操作)
1
2
3
4
5
# Create your models here.
class Table(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=128)
context = models.TextField()
  • 12、将表刷到数据库中
1
2
3
4
root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py makemigrations
//(Django语法)将刚刚在models.py中创建的表对象转换为数据库能够识别的SQL语句,接着将SQL语句刷到指定数据库中
root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py migrate
//migrate:迁移,将表从别的地方迁移至数据库中
  • 13、修改views.py文件,写入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import JsonResponse
from models import Table //导入指定数据库中所需表

# Create your views here.
def zyb_blog(request):

if request.method == "GET":
context = {}
return render(request,'zyb_blog.html',context)
else:
title = request.POST.get("title")
context = request.POST.get("context")
print(title)
print(context)//传到后端
table = Table(title=title,context=context) //写入函数,传入所需值
table.save() //保存传入值,如果获取到值,即传入zyb_blog_table表中
context = {"result": "success"}
return JsonResponse(context)
  • 14、修改views.py文件,查询获取到的数据

    1
    2
    3
    4
    5
    6
    7
    8
    def zyb_blog(request):

    if request.method == "GET":
    context = {}
    ret = Table.objects.all() //将指定数据库所需表中的所有数据全部取出
    context['tables'] = ret
    print(len(ret))//打印ret长度,查看是否成功获取
    return render(request,'zyb_blog.html',context)
  • 15、修改zyb_blog.html,将保存到数据库中的数据渲染到博客主页显示,此时并不会自动刷新并显示

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <html>
    <head>

    </head>
    <body>
    <img src="/static/img/head.jpg">
    {% for table in tables %}
    <h3>{{ table.title}}</h3>
    <p>{{ table.context}}</p>
    {% endfor %}
    <div>
    <p>hello</p>
    <input id="title" type="text" placeholder="请输入标题"><br>
    <textarea id="context" cols="20" rows="20" placeholder="请输入内容"></textarea><br>
    <button id="submit_btn">发布内容</button>
    </div>
    </body>
    <html>
  • 16、修改zyb_blog.js文件,使获取到的数据自动刷新页面

1
2
3
4
5
6
7
8
9
10
$.ajax({
type: "POST",
url: "zyb_blog/",
data: post_data,
success: function(data){
//console.log('return success');
location.reload();
}

});

其他事项

重新启动Django

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
root@theia-ide-abb35e498637-0:/home/openlab/workspace# ls
webDemo
root@theia-ide-abb35e498637-0:/home/openlab/workspace# cd webDemo
root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py runserver 0.0.0.0:8090
Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

September 16, 2020 - 06:35:47
Django version 1.11.29, using settings 'webDemo.settings'
Starting development server at http://0.0.0.0:8090/
Quit the server with CONTROL-C.
[16/Sep/2020 06:35:51] "GET /zyb_blog/ HTTP/1.1" 200 480
[16/Sep/2020 06:35:51] "GET /static/js/jquery-3.3.1.min.js HTTP/1.1" 200 86927
[16/Sep/2020 06:35:51] "GET /static/js/zyb_blog.js HTTP/1.1" 200 444
[16/Sep/2020 06:35:51] "GET /static/img/head.jpg HTTP/1.1" 200 91084

数据库操作

  • 1、查看表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mysql> show tables;
+----------------------------+
| Tables_in_webDemo |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| zyb_blog_table |
+----------------------------+
11 rows in set (0.00 sec)
  • 2、查看表结构
1
2
3
4
5
6
7
8
9
mysql> desc zyb_blog_table;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(128) | NO | | NULL | |
| context | longtext | NO | | NULL | |
+---------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
  • 3、选择数据库的所有数据
1
2
mysql> select * from zyb_blog_table;
Empty set (0.00 sec)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×