1. 程式人生 > >【python】flask入門

【python】flask入門

安裝

>pip install Flask

>pip install Flask-SQLAlchemy

一個小框架:flask_news.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/net_news?charset=utf8' 
db = SQLAlchemy(app)

class News(db.Model):
    ''' 新聞型別 '''
    __tablename__ = 'news'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False) 
    content = db.Column(db.String(2000), nullable=False)
    types = db.Column(db.String(10), nullable=False)
    image = db.Column(db.String(300))
    author = db.Column(db.String(20))
    view_count = db.Column(db.Integer)
    created_at = db.Column(db.DateTime)
    is_valid = db.Column(db.Boolean)

#News.metadata.create_all()
    def __repr__(self):
        return '<News %r>' % self.title #>>>News.query.all()查詢,以此種方式展示<News 'title'>,不然顯示的就是各種編碼地址

@app.route('/hello')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)
>>> from flask_news import db 
>>> db.create_all()
>>> from flask_news import News
>>>
>>> new_obj = News(
...             #中文需要編碼,加utf8
...             title='ORM標題',
...             content='內容',
...             types="百家"
...         )
>>> db.session.add(new_obj)
>>> db.session.commit()
>>> News.query.all()
[<News 'ORM標題'>, <News 'ORM標題'>]

/admin介面顯示資料庫的資料資訊,加分頁,flask_news.py:

from flask import Flask,render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/net_news?charset=utf8'
db = SQLAlchemy(app)

class News(db.Model):
    ''' 新聞型別 '''
    __tablename__ = 'news'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False) 
    content = db.Column(db.String(2000), nullable=False)
    types = db.Column(db.String(10), nullable=False)
    image = db.Column(db.String(300))
    author = db.Column(db.String(20))
    view_count = db.Column(db.Integer)
    created_at = db.Column(db.DateTime)
    is_valid = db.Column(db.Boolean)

#News.metadata.create_all()
    def __repr__(self):
        return '<News %r>' % self.title

@app.route('/')
def index():
    '''新聞的首頁'''
    news_list = News.query.all()
    # news_list = News.query.filter_by(is_valid = 1)  
    return render_template('index.html',news_list = news_list)

@app.route('/cat/<name>/')
def cat(name):
    '''新聞的類別'''
    news_list = News.query.filter(News.types == name)
    #查詢類別為name的新聞資料
    return render_template('cat.html',name = name,news_list = news_list)

@app.route('/detail/<int:pk>/')
def detail(pk):
    '''新聞詳情資訊'''
    new_obj = News.query.get(pk)
    return render_template('detail.html',new_obj = new_obj)

@app.route('/admin/')
@app.route('/admin/<int:page>/')
def admin(page = None):
    '''新聞管理首頁'''
    #如果沒有傳,則表示第一頁
    if page is None:
        page = 1
    # news_list = News.query.all()
    news_list = News.query.paginate(page=page,per_page=5) #分頁
    return render_template('admin/index.html',news_list = news_list)

@app.route('/admin/add/')
def add():
    return render_template('admin/add.html')

@app.route('/admin/update/<int:pk>/')
def update(pk):
    '''新聞詳情資訊'''
    new_obj = News.query.get(pk)
    return render_template('update.html',new_obj = new_obj)

@app.route('/admin/delete/<int:pk>/')
def delete(pk):
    '''新聞詳情資訊'''
    new_obj = News.query.get(pk)
    return render_template('delete.html',new_obj = new_obj)

if __name__ == '__main__':
    app.run(debug=True)

/admin/index.html

{% extends 'admin/base.html' %}
{% block title %}
<title>新聞管理首頁</title>
{% endblock %}
{% block content %}
<table class="table table-striped">
  <thead>
    <tr>
      <th>編號</th>
      <th>新聞標題</th>
      <th>類別</th>
      <th>新增時間</th>
      <th>操作</th>
    </tr>
  </thead>
  <tbody>
  {% for new_obj in news_list.items %}
    <tr>
      <td>{{ new_obj.id }}</td>
      <td>{{ new_obj.title }}</td>
      <td>{{ new_obj.types }}</td>
      <td>{{ new_obj.created_at }}</td>
      <td><a class="btn btn-info" href="{{ url_for('update', pk=new_obj.id) }}">修改</a>
      <a class="btn btn-danger" href="javscript:;" data-url="{{ url_for('delete', pk=new_obj.id) }}">刪除</a></td>
    </tr>
    {% endfor %}
  </tbody>
</table>
<nav aria-label="Page navigation">
  <ul class="pagination">
    <li>
      {% if news_list.has_prev %}
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">«</span>
      </a>
      {% else %}
      {% endif %}
    </li>
    {% for page in news_list.iter_pages() %}
    <li><a href="{{ url_for('admin', page=page) }}">{{ page }}</a></li> <!-- href實現點選1,2,頁面跳轉 -->
    {% endfor %}
    <li>
      <a href="#" aria-label="Next">
        <span aria-hidden="true">»</span>
      </a>
    </li>
  </ul>
</nav>
{% endblock %}
{% block extrajs %}
<script>
  $(function(){
    $('.btn-danger').on('click', function(){
      var btn = $(this);
      if(confirm('確定刪除該記錄嗎?')){
        $.post(btn.attr('data-url'), function(data){
          if (data === 'yes'){
            btn.parents('tr').hide();
          }else{
            alert('刪除失敗');
          }
        })
      }
    })
  })
</script>
{% endblock  %}