The Seven Year Itch.

MENU

Python 实现一个简单的上下文管理器

May 9, 2018 • Read: 298 • Python

# -*- coding: utf-8 -*-
"""
@Created by Seven on 2018-05-09
import os
from flask import (Flask,request....)
"""
from contextlib import contextmanager


@contextmanager
def books_mark():
    print("《", end='')
    yield
    print("》", end='')


with books_mark():
    print("假如给你三天光明", end='')
# -*- coding: utf-8 -*-
"""
@Created by Seven on 2018-05-09
import os
from flask import (Flask,request....)
"""
from flask import Flask
from contextlib import contextmanager
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy

app = Flask(__name__)

class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            raise e


db = SQLAlchemy()


@app.route('/')
def index():
    """
    伪代码
    利用上下文 避免重复性代码
    :return:
    """
    with db.auto_commit():
        user = User(username='111',password='222')
        db.session.add(user)
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code