本文整理汇总了Python中flask.app.Flask.run方法的典型用法代码示例。如果您正苦于以下问题:Python Flask.run方法的具体用法?Python Flask.run怎么用?Python Flask.run使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.app.Flask
的用法示例。
在下文中一共展示了Flask.run方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BaseHTTPService
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [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: remove
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
finally:
if con:
con.close()
def remove(pageid):
con = None
try:
con = lite.connect(DATABASE)
with con:
con.rollback()
cur = con.cursor()
cur.execute("DELETE FROM page WHERE pageid = ?", (pageid,))
cur.execute("DELETE FROM medialinks WHERE pageid = ?", (pageid,))
cur.execute("DELETE FROM otherlinks WHERE pageid = ?", (pageid,))
con.commit()
return "Successfully Removed"
except lite.Error, e:
return str(e)
finally:
if con:
con.close()
@nc4h.route('/remove_submission', methods=["POST"])
def remove_sub():
pageid = request.form['pageid']
message = remove(pageid)
return render_template('mysubmissions.html',message=message)
if __name__ == '__main__':
nc4h.run(host='0.0.0.0',port=2000,debug=True)
示例3: make_response
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
re.findall(href_regexp, raw_response)
response = make_response(raw_response)
# copy response headers
for header in url_response.headers:
for header_prefix in PROXY_RESPONSE_HEADER_PREFIXES:
if header.lower().startswith(header_prefix):
# copy header
response.headers[header] = url_response.headers[header]
break
return response
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", help="debug mode, pause on exception", action="store_true")
parser.add_argument("-b", "--bind", help="bind address", default="0.0.0.0")
parser.add_argument("-p", "--port", help="server port", default=8005, type=int)
parser.add_argument("-i", "--inject", help="inject script", default=None)
args = parser.parse_args()
if args.inject:
with open(args.inject) as f:
PROXY_INJECT_SCRIPT = f.read()
app.run(host=args.bind, port=args.port, debug=args.debug)
示例4: get_user_id
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
elif request.form['password'] != request.form['password2']:
error = 'The two passwords do not match'
elif get_user_id(request.form['username']) is not None:
error = 'The username is alredy taken'
else:
g.db.execute('''insert into user (username, email, pw_hash) values (?, ?, ?)''',
[request.form['username'], request.form['email'],
generate_password_hash(request.form['password'])])
g.db.commit()
flash('You were successfully registered and can login now')
return redirect(url_for('login'))
return render_template('register.html', error=error)
@app.route('/logout')
def logout():
'''
Logs the user out.
:return:
'''
flash('You were logged out')
session.pop('user_id', None)
return redirect(url_for('public_timeline'))
# add some filters to jinja
app.jinja_env.filters['datetimeformat'] = format_datetime
app.jinja_env.filters['gravatar'] = gravatar_url
if __name__ == '__main__':
init_db()
app.run()
示例5: render_template
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
visitor_ratings = app_controller.get_all_visitor_ratings(movie_id)
movie_info = app_controller.get_movie_info(movie_id)
return render_template('all_movie_ratings.html', system_user_ratings=system_user_ratings,
visitor_ratings=visitor_ratings, movie_info=movie_info)
@app.route('/showUserInfo')
def show_user_info():
user_id = request.args.get('userId')
is_system_user = request.args.get('systemUser')
session_id = request.args.get('sessionId')
user_ratings = []
if session_id:
user_ratings = app_controller.get_all_ratings_for_session(session_id.encode('utf-8'))
else:
user_ratings = app_controller.get_all_ratings_for_user(user_id.encode('utf-8'), is_system_user.encode('utf-8'))
user_info = {'user_id':user_id, 'session_id':session_id}
return render_template('user_info.html', user_ratings=user_ratings, user_info=user_info)
@app.route('/compareRecommendationAlgos')
def compare_recommendation_algos():
recommendations, user_id, nimfa_rmse, scikit_rmse = app_controller.get_recommendations_for_system_user();
return render_template('compare_recommendation_algos.html', recommendations=recommendations, user_id=user_id,
nimfa_rmse=nimfa_rmse, scikit_rmse=scikit_rmse)
def ok_response():
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
if __name__ == '__main__':
app.run("0.0.0.0", 9090, debug=True)
示例6: Flask
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
from flask.app import Flask
from flask_restful import Api
from controllers.captchacontroller import CaptchaController
app = Flask(__name__)
api = Api(app)
api.add_resource(CaptchaController, '/captcha/')
app.run(debug=True)
示例7: log_request
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
@app.before_request
def log_request():
logger = getLogger("netman.api")
logger.info("{} : {}".format(request.method, request.url))
if logger.isEnabledFor(DEBUG):
logging.getLogger("netman.api").debug("body : {}".format(repr(request.data) if request.data else "<<empty>>"))
logging.getLogger("netman.api").debug("Headers : " + ", ".join(["{0}={1}".format(h[0], h[1]) for h in request.headers]))
switch_factory = SwitchFactory(MemoryStorage(), ThreadingLockFactory())
switch_session_manager = SwitchSessionManager()
NetmanApi().hook_to(app)
SwitchApi(switch_factory, switch_session_manager).hook_to(app)
SwitchSessionApi(switch_factory, switch_session_manager).hook_to(app)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Netman Server')
parser.add_argument('--host', nargs='?', default="127.0.0.1")
parser.add_argument('--port', type=int, nargs='?', default=5000)
parser.add_argument('--session_inactivity_timeout', type=int, nargs='?')
args = parser.parse_args()
if args.session_inactivity_timeout:
switch_session_manager.session_inactivity_timeout = args.session_inactivity_timeout
app.run(host=args.host, port=args.port)
示例8: Flask
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
import logging
from api.CustomJSONEncoder import CustomJSONEncoder
from api.providers.leboncoin import LeBonCoinProvider
from flask import json, request
from flask.app import Flask
logging.basicConfig(filename='leboncoin.log', level=logging.DEBUG)
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
def providers():
return [
LeBonCoinProvider()
]
@app.route('/api')
def list():
page = request.args.get('page', 1)
location = request.args.get('location', None)
provider = LeBonCoinProvider()
return app.response_class(json.dumps({
'count': provider.count(location),
'houses': provider.list(page=page, location=location)
}), mimetype='application/json')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8888, debug=True)
示例9: _
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
"Happy Tuesday, is everything on track?",
"It's Wednesday, go go go!",
"It's Thursday, why not have a good dinner tonight?",
"Happy Friday, the weekend is coming.",
"Wow Saturday, how would you like to celebrate it?",
"It's Sunday, stay tuned for the upcoming great week. Are you ready for it?"]
greeting = _(greetings[date.today().weekday()])
@app.route('/')
def main():
return render_template("index.html", greeting=greeting)
@app.route('/wechat')
def wechat():
return render_template("wechat.html")
@app.route('/faq')
def faq():
return render_template("faq.html", greeting=greeting)
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
if __name__ == "__main__":
app.run();
示例10: Flask
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
# -*- coding: utf-8 -*-
'''
Created on 2015年10月12日
@author: leilei
'''
from flask.app import Flask
app = Flask(__name__)
@app.route('/<s>')
app.run(host="127.0.0.1", port=80, debug=True)
示例11: check_req_format
# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import run [as 别名]
try:
if response.code == 200:
if check_req_format(response):
pbuff = response.read()
msg = BargainingMessage.deserialize(pbuff)
if not nego.already_received(msg):
if msg.check_msg_fmt(NETWORK):
nego.check_consistency(msg)
nego.append(msg)
nego_db_service.update_nego(session['nid'], nego)
else:
errors.append('Remote node returned an error')
except:
errors.append('A problem occurred while processing the message sent by the remote node')
'''
Prepares rendering
'''
params_tpl = {}
params_tpl['errors'] = '' if len(errors) == 0 else '\n'.join(errors)
params_tpl['wallet_blc'] = get_balance([negotiator.addr1])
params_tpl['chain'] = nego._msgchain
params_tpl['completed'] = True if nego.status in {NEGO_STATUS_CANCELLED, NEGO_STATUS_COMPLETED} else False
return render_template('negotiation.html', params_tpl=params_tpl)
if __name__ == '__main__':
# Comment/uncomment following lines to switch "production" / debug mode
#app.run(host='0.0.0.0', port=8083)
app.run(debug=True, port=8083)