當前位置: 首頁>>代碼示例>>Python>>正文


Python Flask.run方法代碼示例

本文整理匯總了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")
開發者ID:CoreSecurity,項目名稱:HoneySAP,代碼行數:37,代碼來源:service.py

示例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)
開發者ID:Papa2k15,項目名稱:NC4H,代碼行數:32,代碼來源:nc4h.py

示例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)
開發者ID:ronreiter,項目名稱:injection-proxy,代碼行數:31,代碼來源:proxy.py

示例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()
開發者ID:billygoo,項目名稱:dev-365,代碼行數:32,代碼來源:minitwit.py

示例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)
開發者ID:sanjeev90an,項目名稱:MovieRecommender,代碼行數:32,代碼來源:app.py

示例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)
開發者ID:nuxlic,項目名稱:flask-restful-recaptcha,代碼行數:12,代碼來源:runner.py

示例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)
開發者ID:godp1301,項目名稱:netman,代碼行數:31,代碼來源:main.py

示例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)
開發者ID:pgmillon,項目名稱:leboncoin,代碼行數:32,代碼來源:app.py

示例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();
開發者ID:likidu,項目名稱:woojuu.cc,代碼行數:32,代碼來源:app.py

示例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)
開發者ID:zhouleilei,項目名稱:lib,代碼行數:17,代碼來源:app.py

示例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)
開發者ID:LaurentMT,項目名稱:pybargain_demo_client,代碼行數:32,代碼來源:buyer_demo.py


注:本文中的flask.app.Flask.run方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。