我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.views()。
def test_url_with_method(self): from flask.views import MethodView app = flask.Flask(__name__) class MyView(MethodView): def get(self, id=None): if id is None: return 'List' return 'Get %d' % id def post(self): return 'Create' myview = MyView.as_view('myview') app.add_url_rule('/myview/', methods=['GET'], view_func=myview) app.add_url_rule('/myview/<int:id>', methods=['GET'], view_func=myview) app.add_url_rule('/myview/create', methods=['POST'], view_func=myview) with app.test_request_context(): self.assert_equal(flask.url_for('myview', _method='GET'), '/myview/') self.assert_equal(flask.url_for('myview', id=42, _method='GET'), '/myview/42') self.assert_equal(flask.url_for('myview', _method='POST'), '/myview/create')
def test_view_patching(self): app = flask.Flask(__name__) class Index(flask.views.MethodView): def get(self): 1 // 0 def post(self): 1 // 0 class Other(Index): def get(self): return 'GET' def post(self): return 'POST' view = Index.as_view('index') view.view_class = Other app.add_url_rule('/', view_func=view) self.common_test(app)
def test_view_inheritance(self): app = flask.Flask(__name__) class Index(flask.views.MethodView): def get(self): return 'GET' def post(self): return 'POST' class BetterIndex(Index): def delete(self): return 'DELETE' app.add_url_rule('/', view_func=BetterIndex.as_view('index')) c = app.test_client() meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])
def test_endpoint_override(self): app = flask.Flask(__name__) app.debug = True class Index(flask.views.View): methods = ['GET', 'POST'] def dispatch_request(self): return flask.request.method app.add_url_rule('/', view_func=Index.as_view('index')) with self.assert_raises(AssertionError): app.add_url_rule('/', view_func=Index.as_view('index')) # But these tests should still pass. We just log a warning. self.common_test(app)
def test_implicit_head(self): app = flask.Flask(__name__) class Index(flask.views.MethodView): def get(self): return flask.Response('Blub', headers={ 'X-Method': flask.request.method }) app.add_url_rule('/', view_func=Index.as_view('index')) c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Blub') self.assert_equal(rv.headers['X-Method'], 'GET') rv = c.head('/') self.assert_equal(rv.data, b'') self.assert_equal(rv.headers['X-Method'], 'HEAD')
def test_explicit_head(self): app = flask.Flask(__name__) class Index(flask.views.MethodView): def get(self): return 'GET' def head(self): return flask.Response('', headers={'X-Method': 'HEAD'}) app.add_url_rule('/', view_func=Index.as_view('index')) c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'GET') rv = c.head('/') self.assert_equal(rv.data, b'') self.assert_equal(rv.headers['X-Method'], 'HEAD')