一.安装虚拟环境virtualenv

为什么要安装它:当你拥有的项目越多,同时使用不同版本的 Python 工作时,或者起码需要不同版本的 Python 库。可能出现的问题是有一些库文件会破坏向后兼容性,当在你的项目中,出现两个或更多依赖性冲突时,你会怎么做?所以virtualenv提供了一种巧妙的方式来让各项目环境保持独立.

如果你在 Mac OS X 或 Linux 下,下面两条命令可能会适用:

$ sudo easy_install virtualenv

或更好的:

$ sudo pip install virtualenv

如果你用的是 Ubuntu,可以尝试:

$ sudo apt-get install python-virtualenv

全局安装Flask

pip install Flask

创建项目blog

staic放CSS,JS,图片等静态资源;templates放模板文件;run.py是程序入口;config.py配置参数

创建数据库,建表

编码config.py配置操作数据库参数

HOST='127.0.0.1'

PORT=3306

USER='root'

PASSWORD='root'

DATABASE='blogDB'

CHARSET='utf8'

在templates文件夹下创建界面

公用模板layout.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8"/>

<title>我的博客</title>

<style type="text/css">

html,body{

margin: 0;

padding: 0;

}

header,footer{

padding: 30px 40px;

background: #f2f2f2;

color:#666;

}

header a{

padding: 0 20px;

color:#999;

text-decoration: none;

}

header a:hover{

color:#333;

}

footer{

text-align: center;

}

content{

paddding: 30px 40px;

}

</style>

</head>

<body>

<header>

首页

文章列表

</header>

<div id="content">

{% block body %}

{% endblock %}

</div>

<footer>Copyright @ EasyBlog</footer>

</body>

</html>

首页index.html

{% extends 'layout.html' %}

{% block body %}

<h1>欢迎来到我的博客</h1>

<form action="{{url_for('handle')}}" method="post">

<h4>添加文章</h4>

<p>

<input type="text" name="title" placeholder="标题" />

</p>

<p>

<textarea name="content" cols="30" rows="10"
placeholder="内容"></textarea>
function(){ //外汇赠金活动 www.kaifx.cn/activity/

</p>

<button type="submit">提交</button>

</form>

{% endblock %}

文章列表list.html

{% extends 'layout.html' %}

{% block body %}

<style type="text/css">

.row{

padding: 30px;

border: 1px solid #888;

margin: 20px;

}

</style>

<h1>文章列表</h1>

<div id="list">

{% for item in posts %}

<div class="row">

<h4>{{item['title']}}</h4>

<p>{{item['timestamp']}}</p>

</div>

{% endfor %}

</div>

{% endblock %}

文章详情post.html

{% extends 'layout.html' %}

{% block body %}

<h1>文章内容</h1>

<h4>{{post['title']}}</h4>

<h5>{{post['timestamp']}}</h5>

<p>{{post['content']}}</p>

{% endblock %}

编码run.py

# coding:utf-8

import importlib,sys

importlib.reload(sys)

# 引入flask模块

from flask import *

# 关闭警告信息

import warnings

warnings.filterwarnings('ignore')

# 引入MYSQL

import pymysql

from config import *

import time

app = Flask(__name__)

app.config.from_object(__name__)

# 连接数据库

def connectdb():

db = pymysql.connect(host=HOST, port=PORT, db=DATABASE, user=USER, passwd=PASSWORD, charset=CHARSET)

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)#默认元组 设置成字典

return (db,cursor)

# 关闭数据库

def closedb(db,cursor):

cursor.close()

db.close()

# 首页

@app.route('/')

def index():

return render_template('index.html')

# 处理表单提交

@app.route('/handle',methods=['post'])

def handle():

# 获取POST数据

data = request.form

# 连接数据库

(db,cursor) = connectdb()

# 添加数据

cursor.execute("INSERT INTO post(title,content,timestamp) VALUES(%s,%s,%s)",[data['title'],data['content'],str(int(time.time()))])

# 最后添加行的id

post_id = cursor.lastrowid

# 关闭数据库

closedb(db,cursor)

return redirect(url_for('post',post_id=post_id))

# 文章列表页

@app.route('/list')

def list():

# 连接数据库

(db,cursor) = connectdb()

# 查询数据库

cursor.execute('SELECT * FROM post')

data = cursor.fetchall()

# 格化时间

for i in range(0,len(data)):

data[i]['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(float(data[i]['timestamp'])))

# 关闭数据库

closedb(db,cursor)

return render_template('list.html',posts=data)

# 文章详情页

@app.route('/post/<post_id>')

def post(post_id):

# 连接数据库

(db,cursor) = connectdb()

# 查询数据库

cursor.execute('SELECT * FROM post WHERE id=%s',[post_id])

data = cursor.fetchone()

# 格化时间

data['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(data['timestamp'])))

# 关闭数据库

closedb(db,cursor)

return render_template('post.html',post=data)

if __name__ == '__main__':

app.run(debug=True)

其中route()装饰器把一个函数绑定到对应的 URL 上。这样index.html就可以跳转到list.html界面了。要在界面之间进行参数传递,可以在URL绑定相应的变量。比如在文字列表页面list.html跳转到文字详情界面post.html要传递文章id,那么在list.html界面要传递参数id

八.配置venv

在博客项目根目录建立venv文件夹

进入项目后,需要激活相应的环境。在 OS X 和 Linux 上,执行如下操作:

$ . venv/bin/activate

下面的操作适用 Windows:

$ venv\scripts\activate

注意shell 提示符显示的是当前活动的环境

然后python run.py结果如下

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

 * Restarting with stat

 * Debugger is active!

 * Debugger PIN: 330-801-124

ttp://127.0.0.1:5000/ 就是项目根地址.

关闭虚拟环境deactivate命令

九.结束语

快速掌握一门语言,首先要进行快速入门,然后进行简单的实战,最后一步一步由熟悉到精通.

常用开发命令就那些,掌握它,开发能力至少达到70~80%左右


zhuanzhudeyipi
65 声望2 粉丝