本文整理汇总了Python中flask.app.Flask.add_url_rule方法的典型用法代码示例。如果您正苦于以下问题:Python Flask.add_url_rule方法的具体用法?Python Flask.add_url_rule怎么用?Python Flask.add_url_rule使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.app.Flask
的用法示例。
在下文中一共展示了Flask.add_url_rule方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BaseHTTPService
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import add_url_rule [as 别名]
class BaseHTTPService(BaseService):
template_folder = None
application_name = None
def setup_server(self):
super(BaseHTTPService, self).setup_server()
# Create an Flask application for this service using the service name
self.app = Flask(self.application_name or self.__class__.__name__, template_folder=self.template_folder or None)
methods = dir(self)
# Attach each route in the class
for name in [x for x in methods if x.startswith("route_")]:
method = getattr(self, name)
self.app.add_url_rule(method.rule, name, method)
self.logger.debug("Adding handler '%s' for '%s' rule", name, method.rule)
# Attach error handlers in the class
for name in [x for x in methods if x.startswith("error_")]:
method = getattr(self, name)
code = int(name.split("_", 2)[1])
self.app.error_handler_spec[None][code] = method
self.logger.debug("Adding handler '%s' for error code '%d'", name, code)
def run(self):
self.logger.debug("Waiting for clients")
try:
self.app.run(self.listener_address, self.listener_port)
except KeyboardInterrupt:
self.logger.warning("Canceled by the user")
self.stop()
def stop(self):
self.logger.debug("Stopping server")
示例2: __init__
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import add_url_rule [as 别名]
def __init__(self, *args, **kwargs):
super(HacknightNamespace, self).__init__(*args, **kwargs)
def on_hashtag(self, hashtag):
hashtag_value = hashtag.get('value')
gevent.spawn(send_tweets, self, hashtag_value)
def on_test(self, data):
while True:
self.emit('datetime', str(datetime.utcnow()))
gevent.sleep(1)
def main_endpoint(remaining_path):
socketio_manage(request.environ, {'/main': HacknightNamespace}, request)
app.add_url_rule('/socket.io/<path:remaining_path>', 'main', main_endpoint)
@run_with_reloader
def run_server():
#app.run('0.0.0.0', 8080, debug=True)
global app
print 'Starting SocketIO Server with Gevent Mode ...'
app = SharedDataMiddleware(app, {})
http_server = SocketIOServer(('', 80), app, namespace="socket.io", policy_server=False)
http_server.serve_forever()
if __name__ == '__main__':
run_server()
示例3: queue_send
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import add_url_rule [as 别名]
#! /usr/bin/env python
from flask.app import Flask
from flask.globals import request
from zaguan.examples.colors.controller import ColorsController
_msg_queue = []
def queue_send(msg):
_msg_queue.append(msg)
if __name__ == '__main__':
controller = ColorsController()
controller.send_function = queue_send
app = Flask(__name__, static_folder="html")
app.add_url_rule('/<path:filename>', endpoint='static',
view_func=app.send_static_file)
app.debug = True
@app.route("/")
def index(module=None):
html = open("html/index.html").read()
return html + '<script src="js/debug.js" type="text/javascript"></script>'
@app.route("/colors/<action>")
def actions(action):
controller.process_uri(request.url)
return ""
@app.route("/debug/messages")
def debug_send():
global _msg_queue
示例4: SimpleFlaskAppTest
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import add_url_rule [as 别名]
#.........这里部分代码省略.........
}), headers={"Content-Type": "application/json"})
self.assertEqual(resp.status_code, 200, resp.data)
data = self._parse(resp.data)
self.assertEqual(data["f1"], "1")
self.assertEqual(data["f2"], True)
self.assertEqual(data["f3"], "OLALA")
def testMongoEngineForeignKeyField(self):
self.assertEqual(self.TestCol.objects.count(), 2)
class Serializer(BaseSerializer):
fk = fields.MongoEngineIdField(self.TestCol, required=True)
v = Serializer({"fk": "123"})
self.assertEqual(v.validate(), False)
self.assertEqual(v.errors, {'fk': ['Incorrect id: 123']})
v = Serializer({"fk": str(self.TestCol.objects.first().id)})
v.validate()
self.assertEqual(v.errors, {})
self.assertEqual(v.cleaned_data["fk"], self.TestCol.objects.first())
class R(BaseResource):
def post(self, request):
errors, data = self.validate_request(Serializer)
if errors:
return errors
return "OK"
self.app.add_url_rule("/api", view_func=R.as_view("test2"),
methods=["GET", "POST"])
resp = self.client.post("/api", data=json.dumps({}),
headers={"Content-Type": "application/json"})
self.assertEqual(resp.status_code, 400)
data = json.loads(resp.data.decode("utf-8"))
self.assertEqual(data["fk"], ['Field is required'])
def testSerialization(self):
class Col(db.Document):
value = db.StringField()
created = db.DateTimeField(default=datetime.datetime.now)
Col.objects.delete()
Col.objects.create(value="1")
Col.objects.create(value="2")
class S(BaseSerializer):
value = fields.StringField()
created = fields.DateTimeField(read_only=True)
data = S(Col.objects.all()).to_python()
self.assertEqual(len(data), 2)
self.assertEqual(
list(map(lambda i: i["value"], data)),
["1", "2"]
)
#test can't set read only field