def get_flask_app(project_dir): static_folder = os.path.join(project_dir, "build", "assets") app = Flask(__name__, static_folder=static_folder, static_url_path="/static") app.populus_project_dir = project_dir app.route("/")(index_view) return app
def create_app(config, oidc_overrides=None): app = Flask(__name__) app.config.update(config) if oidc_overrides is None: oidc_overrides = {} oidc = OpenIDConnect(app, **oidc_overrides) app.route("/")(oidc.check(index)) return app
class S3Proxy(object): def __init__(self, bucket_name, path, key, secret, host, port): self.bucket_name = bucket_name self.path = path self.key = key self.secret = secret self.host = host self.port = port logging.basicConfig( format='%(asctime)s: %(name)s/%(levelname)-9s: %(message)s', level=logging.INFO) self.s3 = boto.s3.connection.S3Connection(self.key, self.secret) self.bucket = self.s3.get_bucket(self.bucket_name) self.app = Flask(self.__class__.__name__) #self.app.debug = True self.status = self.app.route('/__status')(self.status) self.handle = self.app.route('/<path:path>')(self.handle) def run(self): return self.app.run( host=self.host, port=self.port, ) def status(self): return Response('{"status": "ok"}', mimetype='application/json') def handle(self, path): self.app.logger.debug('Request for path %r', path) self.app.logger.debug('s3://%s/%s%s', self.bucket_name, self.path, path) try: full_path = self.path + path self.app.logger.debug('full_path %r', full_path) if path.endswith('/'): return self.handle_directory(path) key = self.bucket.get_key(full_path) if key is None: # If we can't find a file, try it as a directory ### Note: Some versions of pip will make some requests for what ### should be directories without the trailing slash. keys = self.bucket.list(full_path + '/', '/') try: iter(keys).next() # there are keys to list, so send back a redirect so the client # knows it should be treating this as a directory. self.app.logger.warning( 'path does not end in / but is a directory, redirecting %r', path) return redirect(path + '/') except StopIteration: self.app.logger.warning('Key not found for path and not a directory %r', path) return ('', 404) self.app.logger.info('Found key for path %r', path) return Response(key, mimetype='application/octet-stream') except Exception, e: return (str(e), 404)
def create_app(): app = Flask(__name__) app.config["SQLITE"] = "todos.db" app.config["API_BOOTSTRAP"] = "/static/bootstrap.min.css" app.config["API_BOOTSTRAP"] = "/static/bootstrap.min.css" app.config["ADMIN_EMAIL"] = "*****@*****.**" app.config["ADMIN_PASSWORD"] = "******" bp_api = Blueprint('api', __name__, static_folder='static') api.init_app(bp_api, fn_user_role=fn_user_role, docs=__doc__) api.config(app.config) api.add_resource(Todos) api.add_resource(User) api.add_permission_resource() api.before_request(connect_db) api.after_request(close_db) def make_view(filename): return lambda *args, **kwargs: app.send_static_file(filename) for url, filename in url_views: end = os.path.splitext(filename)[0] app.route(url, endpoint=end)(make_view(filename)) app.before_first_request(before_first_request) app.register_blueprint(bp_api, url_prefix='/api') return app
class Server(Greenlet): def __init__(self, name, addr, *args, **kwargs): Greenlet.__init__(self) self._application = Flask(name) self._server = WSGIServer(addr, self._application, *args, **kwargs) @self._application.errorhandler(404) def error_404(error): log.warning('web handler(%s) not found', request.path) return str(error), 404 @self._application.errorhandler(Exception) def error_500(error): log.exception('web handler(%s) is error(%s)', request.path, error) return str(error), 500 def _run(self): self._server.serve_forever() def close(self): self._server.stop() def getServer(self): return self._server def getApplication(self): return self._application def setHandler(self, handler, url=None, **kwargs): if not url: url = '/' + handler.__name__ self._application.route(url, **kwargs)(handler)
def create_app(config=None): app = Flask(__name__) app.config.from_object("purepage.config_default") if config: app.config.from_object(config) app.url_map.converters['no'] = NoConverter app.route("/webhooks")(Webhooks()) route_views(app) db.init_app(app) github.init_app(app) mail.init_app(app) limiter.init_app(app) bp_api = Blueprint('api', __name__, static_folder='static') api.init_app(app, blueprint=bp_api, docs=__doc__) for x in resources: api.add_resource(x) api.add_resource(Permission, auth=auth) auth.init_api(api, fn_user_role=fn_user_role) app.register_blueprint(bp_api, url_prefix='/api') gen = Gen(api) gen.resjs() gen.resdocs() gen.permission() return app
def create_backend_app(service): from werkzeug.routing import Map # Create the backend_app backend_app = Flask(__name__) backend_app.debug = True # Reset view functions to reset the app backend_app.view_functions = {} backend_app.url_map = Map() backend_app.url_map.converters['regex'] = RegexConverter backend = BACKENDS[service] for url_path, handler in backend.flask_paths.items(): if handler.__name__ == 'dispatch': endpoint = '{0}.dispatch'.format(handler.__self__.__name__) else: endpoint = None backend_app.route( url_path, endpoint=endpoint, methods=HTTP_METHODS)(convert_flask_to_httpretty_response(handler)) return backend_app
def main(): app = Flask(__name__) logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(message)s") logger = logging.getLogger("Extract english terms") extractor = WEBTermExtractor(logger) app.route('/', methods = ['POST'])(extractor.POST) app.route('/', methods = ['GET'])(extractor.GET) app.run(host='', port=8500, threaded=True)
def create_app(config, oidc_overrides=None): app = Flask(__name__) app.config.update(config) if oidc_overrides is None: oidc_overrides = {} oidc = OpenIDConnect(app, **oidc_overrides) app.route('/')(oidc.check(index)) app.route('/api', methods=['GET', 'POST'])( oidc.accept_token(True, ['openid'])(api)) return app
def main(): app = Flask(__name__) logfile, rootFolder = sys.argv[1:3] server = Server(logfile, rootFolder) app.route("/")(server.index) app.route("/loop")(server.loop) app.route("/expansion")(server.expansion) app.route("/directory")(server.getDirectory) app.route("/getFile")(server.getFile) app.run("0.0.0.0",5001,debug=True)
def test_meta_view(): app = Flask(__name__) api = Api(app) app.route('/')(api.meta_view) with app.test_client() as c: resp = c.get("/") assert resp.status_code == 200 assert resp.mimetype == 'text/html' resp = c.get("/?json") assert resp.status_code == 200 assert resp.mimetype == 'application/json'
def create_app(db_uri, datadir=DEFAULT_DATA_DIR, echo=True, pull_password=None, host=None, port=5000): datadir = os.path.abspath(datadir) app = Flask(__name__) app.config.setdefault('SQLALCHEMY_DATABASE_URI', db_uri) app.config.setdefault('SQLALCHEMY_ECHO', echo) app.config.setdefault('PYVO_DATADIR', datadir) app.config.setdefault('PYVO_PULL_PASSWORD', pull_password) if host: server_name = host if port != 80: server_name += ':{}'.format(port) app.config['SERVER_NAME'] = server_name app.jinja_env.undefined = StrictUndefined db.init_app(app) for filter_name in filters.__all__: app.jinja_env.filters[filter_name] = getattr(filters, filter_name) @app.template_global() def url_for_lang(lang_code): args = dict(request.view_args) args['lang_code'] = lang_code return url_for(request.endpoint, **args) @app.template_global() def tr(cs, en): if g.lang_code == 'cs': return cs elif g.lang_code == 'en': return en raise ValueError(g.lang_code) @app.before_first_request def setup(): db_setup(datadir) @app.url_value_preprocessor def pull_lang_code(endpoint, values): if values: g.lang_code = values.pop('lang_code', None) @app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values['lang_code'] = g.lang_code for url, func, options in routes: app.route(url, **options)(func) return app
def flask_app(request, caplog): # Disable flask server logging caplog.setLevel(logging.ERROR, 'werkzeug') app = Flask(__name__) if request.param == 200: # Add root handler to test that FlaskApp processor can detect running # flask app properly both with and without root handler. app.route('/')(lambda: 'Homepage') return app
def test_flask(self): from flask import Flask, g # nolint from dealer.contrib.flask import Dealer app = Flask('test') Dealer(app) self.assertTrue(app.revision) app.route('/')(lambda: g.revision) with app.test_request_context(): client = app.test_client() response = client.get('/') self.assertTrue(app.revision in response.data)
def app(): """App, that registers if request teardown was happened.""" app = Flask(__name__) app.route('/spam')(lambda: 'eggs') app.teardown_happened = False @app.teardown_request def teardown(*_, **__): app.teardown_happened = True return app
def create_app(config): app = Flask(__name__) app.config.from_pyfile(config) app.debug = app.config.get('DEBUG', False) # Setup semi-permanent cache stored in os temp directory try: app.cache_file = os.path.join( tempfile.gettempdir(), 'spectrometer-cache.p') app.cache = pickle.load(open(app.cache_file, "rb")) except IOError: app.cache = {} # Flask profiler is only active when in debug mode profiler = Profiler() profiler.init_app(app) if not app.debug: # Setup Logger logdir = app.config.get('LOG_DIR', '/var/log/spectrometer') logfile = os.path.join(logdir, 'spectrometer.log') logging.getLogger().setLevel(logging.NOTSET) formatter = logging.Formatter('%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s') console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logging.getLogger().addHandler(console_handler) try: file_handler = RotatingFileHandler(logfile, maxBytes=20000000, backupCount=20) file_handler.setFormatter(formatter) logging.getLogger().addHandler(file_handler) log.info('File logger activated.') except IOError: log.warn('Unable to activate File logger. Please ensure that the ' 'log directory ({0}) is writable by the spectrometer user.'.format(logdir)) # Prep resource handlers app.gerrithandler = GerritHandler(app.config['GERRIT_URL']) app.githandlers = {} # Stop Flask debug mode from running the scheduler twice if not app.debug or os.environ.get('WERKZEUG_RUN_MAIN') == 'true': run_scheduler(app) app.route('/')(views.status) app.register_blueprint(gitapi, url_prefix='/git') app.register_blueprint(gerritapi, url_prefix='/gerrit') return app
def create_app(config, oidc_overrides=None): global oidc app = Flask(__name__) app.config.update(config) if oidc_overrides is None: oidc_overrides = {} oidc = OpenIDConnect(app, **oidc_overrides) app.route('/')(oidc.check(index)) app.route('/at')(oidc.check(get_at)) app.route('/rt')(oidc.check(get_rt)) # Check standalone usage rendered = oidc.accept_token(True, ['openid'])(api) app.route('/api', methods=['GET', 'POST'])(rendered) # Check combination with an external API renderer like Flask-RESTful unrendered = oidc.accept_token(True, ['openid'], render_errors=False)(raw_api) def externally_rendered_api(*args, **kwds): inner_response = unrendered(*args, **kwds) if isinstance(inner_response, tuple): raw_response, response_code, headers = inner_response rendered_response = json.dumps(raw_response), response_code, headers else: rendered_response = json.dumps(inner_response) return rendered_response app.route('/external_api', methods=['GET', 'POST'])(externally_rendered_api) return app
class HydroWebServer(): def __init__(self, crop_id): print("Initializing web server") self.svr = Flask(__name__) self.crop_id = crop_id # If HYDRO_SETTINGS environment value points to a config file # override the default configuration self.svr.config.from_envvar('HYDRO_SETTINGS', silent=True) Bootstrap(self.svr) self.svr.route('/', methods=['GET'])(web.views.index.index) def start(self, debug=False): print("Starting web server") self.svr.run(host=HOST, port=PORT, debug=debug)
def test_flask(): from flask import Flask, g from dealer.contrib.flask import Dealer app = Flask('test') Dealer(app) assert app.revision app.route('/')(lambda: "%s - %s" % (g.revision, g.tag)) with app.test_request_context(): client = app.test_client() response = client.get('/') assert app.revision in response.data.decode('utf-8') assert app.tag in response.data.decode('utf-8')
def build_app(self): """Build app. Put url-map type converters in place, and then setup REST API.""" app = Flask(self.index.name) app.url_map.converters['list'] = ListConverter app.url_map.converters['float'] = FloatConverter def finder(*args, **kwargs): return self.find_response(*args, **kwargs) def sleeper(*args, **kwargs): return self.sleep_response(*args, **kwargs) app.route(self.find_rule)(finder) app.route(self.sleep_rule)(sleeper) return app
def app(): _app = Flask(__name__) obscure.Obscure(_app, SALT) # works for test, but use flask.config def invoice(customer_id): """Show obfuscated customer number. Routes for each filter are created like: /invoice/b32/<b32:customer_id> /invoice/b64/<b64:customer_id> /invoice/hex/<hex:customer_id> /invoice/tame/<tame:customer_id> Arg: customer_id: actual customer number This number, while obfuscated in the URL, has been converted by the in the url_map.converters at this point. Return string: {obscure method}#{obscured customerID} """ encoder = request.url_rule.endpoint template = '{{ encoder }}#{{ customer_id|%s }}' % encoder return render_template_string(template, **locals()) for f in FILTERS: url = '/invoice/%s/<%s:customer_id>' % (f, f) invoice = _app.route(url, endpoint=f)(invoice) return _app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) api.init_app(app) app.route('/',) api.add_resource(AutocompleteAPI.AutoCompleteLocation, '/film/locations/autocomplete', endpoint = 'filmlocations_auto_complete') api.add_resource(FilmsAtLocationsAPI.FilmsAtLocations, '/film/locations/<string:location>', endpoint = 'film_locations') api.add_resource(FindNearestFilmsAtLocationAPI.FindNearest7FilmsAtLocation, '/film/7nearme/lat/<float:lat>/<string:lat_sign>/lng/<float:lng>/<string:lng_sign>', endpoint = 'films_near_me') from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
class AppConfigTest(object): def setUp(self): self.app = Flask(import_name=__name__) def tearDown(self): self.app = None def add_route(self, path): # Flask checks the name of the function to ensure that iew mappings # do not collide. We work around it by generating a new function name # for the path def function_to_rename(): return 'STUBBED: %s' % path function_to_rename.__name__ = 'func_%s' % path self.app.route(path)(function_to_rename)
def decorator(f): @wraps(f) @handle_client_errors def wrapped_f(*f_args, **f_kwargs): data = f(*f_args, **f_kwargs) if isinstance(data, PaginatedResult): return jsonify(serialize(data, PaginatedResultSchema)) return jsonify(data=data) return Flask.route(app, url, *args, **kwargs)(wrapped_f)
def get_app(cls): """ Contruct a Flask object from the bound methods. """ app = Flask(__name__) for func, data, kwdata in cls.bound: @functools.wraps(func) def wrapper(*args, **kwargs): if u'serverid' in kwargs: serverid = int(kwargs[u'serverid']) for server in Server.get_instances(): if server.id == serverid: del kwargs[u'serverid'] return json.dumps(func(server, *args, **kwargs)) return abort(404) return json.dumps(func(*args, **kwargs)) wrapper.__name__ = unicode(id(wrapper)) print(data[0]) app.route(*data, **kwdata)(wrapper) return app
class Logicoma(object): def __init__(self, config_path='configs/logicoma.json', other_opts={}): self.app = Flask('Logicoma') self.app.route('/', methods=['post'])(self.hook) self.other_opts = other_opts self.load_config(config_path) def load_config(self, config_path): with open(config_path) as fp: conf = json.load(fp) conf.update(self.other_opts) self.token = conf['token'] self.debug = conf.get('debug', False) self.handlers = [handlers.load_from_config(s) for s in conf['handlers']] def run(self, *args, **kwargs): return self.app.run(*args, **kwargs) def dispatch(self, text): for h in self.handlers: response = h.handle(text) if response is not None: response_json = json.dumps(response) return (response_json, 200, {'Content-Type': 'application/json'}) return ('', 200, {}) def hook(self): try: payload = request.form logger.debug("payload: %s", payload) if self.debug or payload and payload.get('token') == self.token: if 'text' in payload and payload.get('user_id') != 'USLACKBOT': return make_response(self.dispatch(payload.get('text'))) else: return Response(status=200) else: return Response(status=400) except: logger.exception('got exception on handler') return Response(status=500)
def test_metafile(tmpdir): metafile = tmpdir.join("meta.json") json.dump({"$xxx": "test", "$roles": {}}, metafile.open("w")) app = Flask(__name__) api = Api(app, metafile=metafile.strpath) class Hello: """docstring for Hello""" def get(self): """Get hello""" api.add_resource(Hello) app.route('/')(api.meta_view) with app.test_client() as c: resp = c.get("/", headers={'Accept': 'application/json'}) assert resp.status_code == 200 assert resp_json(resp)["$xxx"] == "test" assert resp_json(resp)["$roles"] == {} assert resp_json(resp)["hello"]["$desc"] == "docstring for Hello" assert resp_json(resp)["hello"]["get"]["$desc"] == "Get hello"
def route(self, *args, **kwargs): ''' route: Wraps the regular Flask.route functionality, takes the methods out of the route and adds them to the dictionary of endpoints, used for the discovery request. ''' route = args[0] for info in self.endpoints.values(): if info['url'] == route: info['methods'] += kwargs['methods'] break return Flask.route(self, *args, **kwargs)
class Perfume(object): def __init__(self, name, debug=False): '' self.app = Flask(name) self.app.debug = debug self._load() def _load(self): "Updates the app's routes with all methods." for name in dir(self): method = self.__getattribute__(name) try: route = method.perfume_route args = method.perfume_args except AttributeError: continue self.app.route(route, **args)(method) def run(self, *args, **kwds): self.app.run(*args, **kwds)
def create_app(test=False): app = Flask(__name__) app.config["ADMIN_EMAIL"] = "*****@*****.**" app.config["ADMIN_PASSWORD"] = "******" if test: app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" app.config["SQLALCHEMY_ECHO"] = True else: db_path = os.path.join(app.root_path, "todos.db") app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_path db.init_app(app) bp_api = Blueprint('api', __name__, static_folder='static') api.init_app(app, blueprint=bp_api, docs=__doc__) auth.init_api(api, fn_user_role=fn_user_role) api.add_resource(Todos) api.add_resource(User) api.add_resource(Permission, auth=auth) api.add_resource(ApiInfo, api=api) def make_view(filename): return lambda *args, **kwargs: app.send_static_file(filename) for url, filename in url_views: end = os.path.splitext(filename)[0] app.route(url, endpoint=end)(make_view(filename)) app.before_first_request(before_first_request) app.register_blueprint(bp_api, url_prefix='/api') gen = Gen(api) gen.resjs('static/js/res.js') gen.resdocs('static/resdocs.html', resjs='/static/js/res.js', bootstrap='/static/css/bootstrap.min.css') gen.permission('static/permission.html', resjs='/static/js/res.js', bootstrap='/static/css/bootstrap.min.css', vuejs='/static/js/vue.js') return app
from flask import Flask db = Flask('') db.route('/css/index.css') def index(): return open('./templates/index.css', 'r').read() if True: db.run()
def app_loader(name): APP = Flask(name, template_folder=os.path.join(DOCS_SERVER_PATH, 'static', 'templates'), static_url_path="/static", static_folder=STATIC_LOCATION) APP.config.from_object(name) APP.route = prefix_route(APP.route, SCRIPT_NAME) @APP.route('/xstatic/<name>/', defaults=dict(filename='')) @APP.route('/xstatic/<name>/<path:filename>') def files(name, filename): base_path = _xstatic(name) if base_path is None: abort(404) if not filename: abort(404) return send_from_directory(base_path, filename) @APP.route('/mss_theme/<name>/', defaults=dict(filename='')) @APP.route('/mss_theme/<name>/<path:filename>') def mss_theme(name, filename): if name != 'img': abort(404) base_path = os.path.join(DOCS_SERVER_PATH, 'static', 'img') return send_from_directory(base_path, filename) def get_topmenu(): if "mscolab" in " ".join(sys.argv): menu = [ (url_for('index'), 'Mission Support System', ( (url_for('about'), 'About'), (url_for('install'), 'Install'), (url_for('help'), 'Help'), )), ] else: menu = [ (url_for('index'), 'Mission Support System', ( (url_for('about'), 'About'), (url_for('install'), 'Install'), (url_for("plots"), 'Gallery'), (url_for('help'), 'Help'), )), ] return menu APP.jinja_env.globals.update(get_topmenu=get_topmenu) def get_content(filename, overrides=None): markdown = Markdown(extensions=["fenced_code"]) content = "" if os.path.isfile(filename): with codecs.open(filename, 'r', 'utf-8') as f: md_data = f.read() md_data = md_data.replace(':ref:', '') if overrides is not None: v1, v2 = overrides md_data = md_data.replace(v1, v2) content = markdown.convert(md_data) return content @APP.route("/index") def index(): return render_template("/index.html") @APP.route("/mss/about") @APP.route("/mss") def about(): _file = os.path.join(DOCS_SERVER_PATH, 'static', 'docs', 'about.md') img_url = url_for('overview') overrides = ['![image](/mss/overview.png)', f'![image]({img_url})'] content = get_content(_file, overrides=overrides) return render_template("/content.html", act="about", content=content) @APP.route("/mss/install") def install(): _file = os.path.join(DOCS_SERVER_PATH, 'static', 'docs', 'installation.md') content = get_content(_file) return render_template("/content.html", act="install", content=content) @APP.route("/mss/plots") def plots(): if STATIC_LOCATION != "" and os.path.exists( os.path.join(STATIC_LOCATION, 'plots.html')): _file = os.path.join(STATIC_LOCATION, 'plots.html') content = get_content(_file) else: content = "Gallery was not generated for this server.<br>" \ "For further info on how to generate it, run the " \ "<b>gallery --help</b> command line parameter of mswms.<br>" \ "An example of the gallery can be seen " \ "<a href=\"https://mss.readthedocs.io/en/latest/gallery/index.html\">here</a>" return render_template("/content.html", act="plots", content=content) @APP.route("/mss/code/<path:filename>") def code(filename): download = request.args.get("download", False) _file = os.path.join(STATIC_LOCATION, 'code', filename) content = get_content(_file) if not download: return render_template("/content.html", act="code", content=content) else: with open(_file) as f: text = f.read() return Response( "".join([ s.replace("\t", "", 1) for s in text.split("```python")[-1].splitlines( keepends=True) ][1:-2]), mimetype="text/plain", headers={ "Content-disposition": f"attachment; filename={filename.split('-')[0]}.py" }) @APP.route("/mss/help") def help(): _file = os.path.join(DOCS_SERVER_PATH, 'static', 'docs', 'help.md') content = get_content(_file) return render_template("/content.html", act="help", content=content) @APP.route("/mss/imprint") def imprint(): _file = os.path.join(DOCS_SERVER_PATH, 'static', 'docs', 'imprint.md') content = get_content(_file) return render_template("/content.html", act="imprint", content=content) @APP.route('/mss/favicon.ico') def favicons(): base_path = icons("16x16", "favicon.ico") return send_file(base_path) @APP.route('/mss/logo.png') def logo(): base_path = icons("64x64", "mss-logo.png") return send_file(base_path) @APP.route('/mss/overview.png') def overview(): base_path = os.path.join(DOCS_SERVER_PATH, 'static', 'img', 'wise12_overview.png') return send_file(base_path) return APP
user_id = getUserID(login_session['email']) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id output = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("Now logged in as %s" % login_session['username']) return output app.route('/fbdisconnect') def fbdisconnect(): facebook_id = login_session['facebook_id'] # The access token must me included to successfully logout access_token = login_session['access_token'] url = 'https://graph.facebook.com/%s/permissions?access_token=%s'\ %(facebook_id,access_token) h = httplib2.Http() result = h.request(url, 'DELETE')[1] return "you have been logged out" ###########################3 gogoole connect ##########3 @app.route('/gconnect', methods=['POST'])
def safe(func): def wrapper(*args, **argkv): try: return func(*args, **argkv) except Exception, e: logger.exception(repr(e)) return None wrapper.__doc__ = func.__doc__ wrapper.__name__ = func.__name__ wrapper.__module__ = func.__module__ return wrapper app.route = safe(app.route) @safe def load_ignore(): with open(conf.IGNORE_FILE, 'r') as f: return [l.strip() for l in f] @safe def add_ignore_word(word): with open(conf.IGNORE_FILE, 'a') as f: f.write(word + '\n') def _product_nodes(product):
from flask import Flask, jsonify, request app = Flask(__name__) countries = [{'name' : 'Singapore'}, {'name' : 'Malaysia'}, {'name' : 'Thailand'} #Creating a list of array @app.route('/', methods=['GET']) def test(): return jsonify({'countries' : countries}) @app.route('/countries/<string:name>', methods={['GET']) def returnOne(name): countries = [countries for countries in countries if countries['name'] == name] return jsonify({'countries' : countries[0]}) @app.route('/countries', methods=['POST']) def addOne(): countries = {'name' : request.json['name']} countries.append(countries) return jsonify({'countries' : countries}) #return value countries with the value of countries #POST request (BODY SECTION: create a new value #{'name' : "Korea"} @app.route('/countries/<string:name>', methods={['PUT']) def editOne(name): countries = [countries for countries in countries if countries['name'] == name] countries[0]['name'] = request.json['name']
# coding=utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') from flask import Flask from users import user_info from orders import order_blu from cart import cart_blu # 创建Flask应用程序实例 app = Flask(__name__) # 循环引用: 让其中一方延迟导入或者不导入 app.route("/user_info")(user_info) # 3. 使用app对象注册蓝图 app.register_blueprint(order_blu) app.register_blueprint(cart_blu, url_prefix="/cart") @app.route('/') def index(): return 'index' # 用户模块 # 以下代码抽取到users.py文件中 # @app.route("/user_info") # def user_info(): # return "user_info"
get_car_options = [] for f in cars: if not(f['Identification']['ID']) in get_car_options: get_car_options.append(f['Identification']['ID']) y = '' for x in get_car_options: y = y + Markup("<option value=\"" + x + "\">" + x + "</option>") return y @app.route("/") def render_main(): with open('cars.json') as cars_data: cars = json.load(cars_data) return render_template('home.html', options = get_car_options(cars), car_options = get_car_options(cars)) app.route("/response", methods = ['GET']) def render_response(): with open('cars.json') as cars_data: cars = json.load(cars_data) car = request.args['CarSelected'] factT = "" factCM = "" factHM = "" factHP = "" for data in cars: if car == data["Identification"]["ID"]: #data["Classification"]["Horsepower"]["City mpg"]["Highway mpg"] factT = data["Identification"]["Classification"] factCM = data["Fuel Information"]["City mpg"] factHM = data["Fuel Information"]["Highway mpg"] factHP = data["Engine Information"]["Horsepower"]
resp.headers['Content-type'] = 'application/json' if LATENCY: time.sleep(LATENCY) return resp if 'methods' in kwargs: kwargs['methods'].append('OPTIONS') registered_func = ar(*args, **kwargs)(wrap) registered_func._orig = func return registered_func return decorator app.route = corsify @app.route('/api/v1/account/login/', methods=['POST']) def login(): assertion = request.form.get('assertion') audience = request.form.get('audience') is_native = int(request.form.get('is_native')) print 'Attempting verification:', audience, is_native email = persona.verify_assertion(assertion, audience, is_native) if not email: return make_response('{"error": "bad_assertion"}', 403) # At this point, we know that the user is a valid user.
song_index=song_index, category="j-rock", song=song) @app.route('/britpop') def britpop(): BASE_DIR = '/Users/Ousyoukan/Desktop/microblog/app' song = request.args.get('song', '01', type=str) song_index = string.atoi(song) - 1 title = get_title('britpop') file_path1 = BASE_DIR + '/static/data/britpop/' lyric = open(file_path1 + title[song_index] + '.txt').read() return render_template("listen.html", lyric=lyric, title=title, song_index=song_index, category="britpop", song=song) app.route('/about') def about(): return render_template("about.html") app.run(debug=True)
class ServerFlaskCommunicator(ServerCommunicator): def __init__(self) -> None: super().__init__() static_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'role') self._app = Flask(__name__, template_folder=os.path.join(static_path, 'templates'), static_folder=os.path.join(static_path, 'static')) self._app.config['SECRET_KEY'] = ConfigurationManager( ).runtime_config.secret_key self._socketio = ServerSocketIO(self._app, max_http_buffer_size=1e20, async_handlers=True, ping_timeout=3600, ping_interval=1800, cors_allowed_origins='*') logging.getLogger('werkzeug').setLevel(logging.ERROR) def on(self, event: ClientEvent) -> Callable[[Callable], Any]: return self._socketio.on(event2message(event)) def route(self, rule: str, **options: Any): return self._app.route(rule, **options) def invoke(self, event: ClientEvent, *args, callee: Optional[ClientId] = None, **kwargs): room_id = request.sid if callee is not None: with self._client_node_ctx_mgr.get_by_client(callee) as c_node_ctx: room_id = c_node_ctx.comm_id return emit(event2message(event), *args, room=room_id, **kwargs) def invoke_all(self, event: ClientEvent, payload: Optional[Dict[str, Any]] = None, *args, callees: Optional[Iterable[ClientId]] = None, **kwargs): msg = event2message(event) if callees is None: if payload is None: return emit(msg, *args, **kwargs, broadcast=True) else: return emit(msg, payload, *args, **kwargs, broadcast=True) else: res = list() for node_id, client_ids in self._client_node_ctx_mgr.cluster_by_node( callees).items(): if payload is None: payload = dict() payload['selected_clients'] = list(client_ids) with self._client_node_ctx_mgr.get_by_node( node_id) as c_node_ctx: room_id = c_node_ctx.comm_id res.append( emit(msg, payload, *args, room=room_id, **kwargs)) return res def run_server(self) -> None: self._socketio.run(self._app, host=self._host, port=self._port) def handle_disconnection(self) -> Iterable[ClientId]: return self._handle_disconnection(request.sid) def handle_reconnection(self) -> Iterable[ClientId]: return self._handle_reconnection(request.sid) def activate(self, node_id: NodeId, client_ids: Iterable[ClientId]) -> None: self._activate(node_id, request.sid, client_ids)
engine = create_engine("sqlite:///hawaii.sqlite") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station session = Session(engine) # Flask setup app = Flask(__name__) #Flask routes app.route("/") def welcome(): return (f'Welcome to Hawaii Climate Analysis API!<br/>' f'Available Routes:<br/>' f'/api/v1.0/Precipitation<br/>' f'/api/v1.0/stations<br/>' f'/api/v1.0/stations<br/>' f'api/v1.0/tobs<br/>' f'api/v1.0/temp/start</br>' f'api/v1.0/temp/start/end</br>') # # precipitation @app.route('/api/v1.0/Precipitation')
def not_logged_in_route(*args, **kwargs): ''' same logic as logged_in_route, but no need to wrap f with a checker ''' def inner(f): return __router(*args, **kwargs)(f) return inner def doNotUseAppRoute(*args, **kwargs): err = 'Do not use @app.route, use @logged_in_route or @not_logged_in_route' raise ValueError(err) app.route = doNotUseAppRoute def is_logged_in(f: Callable) -> Callable: ''' this decorator ensures that the user is logged in when attempting to access a route (except /login) ''' @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: return redirect(url_for('login')) return wrap
# we are on a subdomain - remove cookie for this and all other subdomains response.set_cookie('session', '', expires=0, domain='.' + domain.split('.', 1)[-1]) return response share_redirects = { 'mendokusaii': 'mendokusaii', } for key, username in share_redirects.items(): route = functools.partial(redirect, f'/apex/games/{username}', code=308) route.__name__ = f'streamer_redirect_{key}' app.route('/' + key)(route) # @app.route('/eeveea_') # def eeveea_games(): # return render_games_list(User.user_id_index.get(347766573), public=True, meta_title='eeveea_') # # @app.route('/mendokusaii') # def mendokusaii_games(): # return render_games_list(User.user_id_index.get(-3), public=True, meta_title='Mendokusaii') # # @app.route('/heylauren') # def heylauren_games(): # return render_games_list(User.user_id_index.get(-420), public=True, meta_title='heylauren') # # @app.route('/shroud') # def shroud_games():
class SnapServer(Application): OFF = "turnoff" def __init__(self, port, argparser=None): Application.__init__(self, argparser) self.port = int(port) self.flask = Flask(__name__) logging.basicConfig(level=logging.DEBUG) self.current_auth_nick = self.OFF self.nicknames = {} self.lock = RLock() CORS(self.flask) self.loop = None self.route() def signal_handler(self, signal, frame): print("Received SIGINT, closing...") if self.loop is not None: self.loop.stop() def route(self): self.flask.route('/admin', methods=['GET', 'POST'])(self.render_admin_page) self.flask.route('/admin/nicknames', methods=['GET'])(self.get_admin_nicknames) self.flask.route('/admin/active_nickname', methods=['GET'])(self.get_admin_active_nickname) self.flask.route('/set_rgb_matrix', methods=['POST'])(self.set_rgb_matrix) self.flask.route('/is_authorized/<nickname>', methods=['GET'])(self.is_authorized) self.flask.route('/authorize', methods=['POST'])(self.authorize) self.flask.route('/get_nickname', methods=['GET'])(self.get_nickname) def get_admin_active_nickname(self): return dumps(self.current_auth_nick) def get_admin_nicknames(self): # update user table self.check_nicknames_validity() return dumps( sorted(self.nicknames.keys(), key=lambda x: self.nicknames[x]["appeared"])) def check_nicknames_validity(self): with self.lock: temp_dict = {} for nick, timestamps in self.nicknames.items(): if time() - timestamps["last_seen"] < 20: temp_dict[nick] = timestamps else: if nick == self.current_auth_nick: self.current_auth_nick = self.OFF self.erase_all() self.nicknames = temp_dict def render_admin_page(self): res = render_template('admin.html') return res def authorize(self): nick = request.get_data() with self.lock: if nick in list(self.nicknames.keys()) + [self.OFF]: self.current_auth_nick = nick self.erase_all() return '' return 'No such client', 404 @staticmethod def scale(v): return min(1, max(0., float(v) / 255.)) def set_rgb_matrix(self): try: data = request.get_data().split(':') with self.lock: if data.pop(0) == self.current_auth_nick: r = 0 c = 0 while data: red = data.pop(0) green = data.pop(0) blue = data.pop(0) self.model.set_pixel( r, c, map(self.scale, [red, green, blue])) if c < self.model.width - 1: c += 1 else: c = 0 r += 1 except Exception as e: print(repr(e)) sys.exc_clear() return '' def erase_all(self): self.model.set_all('black') return '' def is_authorized(self, nickname): with self.lock: if nickname in self.nicknames: self.nicknames[nickname]["last_seen"] = time() return str(nickname == self.current_auth_nick) def get_nickname(self): rand_id = petname.generate() with self.lock: while rand_id in self.nicknames.keys(): rand_id = petname.generate() self.nicknames[rand_id] = {"appeared": time(), "last_seen": time()} return rand_id def run(self): # open('http://snap.berkeley.edu/run') signal.signal(signal.SIGINT, self.signal_handler) self.loop = IOLoop() http_server = HTTPServer(WSGIContainer(self.flask)) http_server.listen(self.port) self.loop.start()
"""the below code blow has been done with """ # app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@127.0.0.1:5432/sales_demo' # app.config['SECRET_KEY'] = 'KenyaYetuMoja' # app.config['DEBUG'] = True db = SQLAlchemy(app) from models.inventories import Inventories from models.sales import Sales @app.before_first_request def create_tables(): db.create_all() """ passing values through a route 1.create the route <id>- the id no. that to be passed the func also gets that that id the system will get every sale you make will be for a specific product.. ----------------------------- passing strings app.route('/test/<name>') def test(name): return name ---------------------- @app.route('/test/<num1>/<num2>') def test(num1,num2): print( int(num1)+int(num2)) return 'yes'
@apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "commits": 153 }, { "date": "2015-01-08T00:00:00.000Z", "commits": 192 } ] """ app.route('/{}/<owner>/<repo>/timeseries/commits'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(app, ghtorrent.commits)) """ @api {get} /:owner/:repo/forks Forks by Week @apiName ForksByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "forks": 13 }, {
return redirect('/admin/') conn = sqlite3.connect('my.db') conn.text_factory = lambda x: unicode(x, "cp936", "ignore") cursor = conn.cursor() sql = "select time,content,id from liuyan " cursor.execute(sql) liuyan = cursor.fetchall() cursor.close() conn.close() return render_template('glpl.html', liuyan=liuyan) @app.route('/dliuyan/<id>') def dliuyan(id): if not session.get('login'): return redirect('/admin/') conn = sqlite3.connect('my.db') cursor = conn.cursor() sql = "delete from liuyan where id = ?" cursor.execute(sql, id) conn.commit() cursor.close() conn.close() return redirect('/glpl/') app.route('/grzx/') if __name__ == '__main__': app.debug = True app.run()
print(sys.exc_info()) abort(422) ''' @TODO implement endpoint PATCH /drinks/<id> where <id> is the existing model id it should respond with a 404 error if <id> is not found it should update the corresponding row for <id> it should require the 'patch:drinks' permission it should contain the drink.long() data representation returns status code 200 and json {"success": True, "drinks": drink} where drink an array containing only the updated drink or appropriate status code indicating reason for failure ''' app.route('/drinks/<int:id>', methods=['PATCH']) @requires_auth("post:drinks") def edit_drink(jwt,id): drink = Drink.query.filter(Drink.id == id).one_or_none() if drink != None: body = request.get_json() title = body.get('title', None) recipe = body.get('recipe', []) if title != None : drink.title=title if recipe != [] : drink.recipe = json.dumps([recipe]) account.update() else : abort(404)
#@app.route('/drinks', methods=['POST']) #@requires_auth('post:drinks') #def create_drink(jwt): # title = request.json.get('title', None) # recipe = request.json.get('recipe', None) # # byTitle = Drink.query.filter(Drink.title == title).all() # if len(byTitle): # return abort(422) # newDrink = Drink(title=title, recipe=json.dumps(recipe)) # newDrink.insert() # return jsonify({'success': True, 'drinks': [newDrink.long()]}) #Code example provided by Udacity app.route('/drinks', methods=['POST']) @requires_auth('post:drinks') def create_drink(): drink = request.get_json()['drink'] created_drink = Drink(id=drink['id'], title=drink['title'], recipe=drink['recipe']) try: Drink.insert(created_drink) except: abort(404) return jsonify({ "success": True,
class TestProgrammatic(InstrumentationTest, TestBase, WsgiTestBase): def setUp(self): super().setUp() self.app = Flask(__name__) FlaskInstrumentor().instrument_app(self.app) self._common_initialization() self.env_patch = patch.dict( "os.environ", { "OTEL_PYTHON_FLASK_EXCLUDED_URLS": "http://localhost/excluded_arg/123,excluded_noarg" }, ) self.env_patch.start() self.exclude_patch = patch( "opentelemetry.instrumentation.flask._excluded_urls", Configuration()._excluded_urls("flask"), ) self.exclude_patch.start() def tearDown(self): super().tearDown() self.env_patch.stop() self.exclude_patch.stop() with self.disable_logging(): FlaskInstrumentor().uninstrument_app(self.app) def test_uninstrument(self): resp = self.client.get("/hello/123") self.assertEqual(200, resp.status_code) self.assertEqual([b"Hello: 123"], list(resp.response)) span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) FlaskInstrumentor().uninstrument_app(self.app) resp = self.client.get("/hello/123") self.assertEqual(200, resp.status_code) self.assertEqual([b"Hello: 123"], list(resp.response)) span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) # pylint: disable=no-member def test_only_strings_in_environ(self): """ Some WSGI servers (such as Gunicorn) expect keys in the environ object to be strings OpenTelemetry should adhere to this convention. """ nonstring_keys = set() def assert_environ(): for key in request.environ: if not isinstance(key, str): nonstring_keys.add(key) return "hi" self.app.route("/assert_environ")(assert_environ) self.client.get("/assert_environ") self.assertEqual(nonstring_keys, set()) def test_simple(self): expected_attrs = expected_attributes( {"http.target": "/hello/123", "http.route": "/hello/<int:helloid>"} ) self.client.get("/hello/123") span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.assertEqual(span_list[0].name, "/hello/<int:helloid>") self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER) self.assertEqual(span_list[0].attributes, expected_attrs) def test_not_recording(self): mock_tracer = Mock() mock_span = Mock() mock_span.is_recording.return_value = False mock_tracer.start_span.return_value = mock_span mock_tracer.use_span.return_value.__enter__ = mock_span mock_tracer.use_span.return_value.__exit__ = mock_span with patch("opentelemetry.trace.get_tracer") as tracer: tracer.return_value = mock_tracer self.client.get("/hello/123") self.assertFalse(mock_span.is_recording()) self.assertTrue(mock_span.is_recording.called) self.assertFalse(mock_span.set_attribute.called) self.assertFalse(mock_span.set_status.called) def test_404(self): expected_attrs = expected_attributes( { "http.method": "POST", "http.target": "/bye", "http.status_text": "NOT FOUND", "http.status_code": 404, } ) resp = self.client.post("/bye") self.assertEqual(404, resp.status_code) resp.close() span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.assertEqual(span_list[0].name, "HTTP POST") self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER) self.assertEqual(span_list[0].attributes, expected_attrs) def test_internal_error(self): expected_attrs = expected_attributes( { "http.target": "/hello/500", "http.route": "/hello/<int:helloid>", "http.status_text": "INTERNAL SERVER ERROR", "http.status_code": 500, } ) resp = self.client.get("/hello/500") self.assertEqual(500, resp.status_code) resp.close() span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.assertEqual(span_list[0].name, "/hello/<int:helloid>") self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER) self.assertEqual(span_list[0].attributes, expected_attrs) def test_exclude_lists(self): self.client.get("/excluded_arg/123") span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 0) self.client.get("/excluded_arg/125") span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.client.get("/excluded_noarg") span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.client.get("/excluded_noarg2") span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1)
from flask import Flask, request from flask_cors import CORS import sqlalchemy app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') import models models.db.init_app(app) def root(): return 'ok' app.route('/', methods=["GET"])(root) def signup(): try: user = models.User(email=request.json["email"], password=request.json["password"]) models.db.session.add(user) models.db.session.commit() return {"user": user.to_json()} except sqlalchemy.exc.IntegrityError: return {"message": "email already taken"}, 400 app.route('/users', methods=["POST"])(signup)
class FlaskManager(Manager): """ """ def render_json(self, obj): return jsonify(obj) # has correct header type set def get_argument(self, name, default_value=None): return request.args.get(name, default_value) def render_template(self, template_name, **kwargs): values = {} for f in app.get_context_processors(): values.update(f(self)) values.update(kwargs) return render_template(template_name, **values) def error(self, error_number): return self.render_template("%s.html" % error_number), error_number def redirect(self, url): return redirect(url) def url_for(self, name): return url_for(name) @property def request(self): return request def run(self): self.app = Flask(__name__, template_folder=self.get_template_folder(), static_folder=self.get_static_folder()) self.app.config.update(WTF_CSRF_CHECK_DEFAULT=False) self.app.config["CSS"] = self.CSS self.app.config.update(self.config) self.csrf = CSRFProtect(self.app) ## Add routes: for path, methods, f, kwargs in app._data.routes: ## Add the route: self.app.route(path, methods=methods, **kwargs)(wrap_function(self, f)) ## Add filters: for f in app._data.filters: ## Add the template filter function: self.app.template_filter()(wrap_function(self, f)) self.app.run(debug=1, port=self.port) def load_secret_key(self, name): key = self._load_secret_key(name) self.app.secret_key = key def after_request(self, f): """ Decorator """ return self.app.after_request(f) def template_filter(self): """ Decorator """ def decorator(f): self.app.template_filter()(f) return decorator def login_required(self, f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get("logged_in"): return redirect(url_for("login", next=request.url)) return f(*args, **kwargs) return decorated_function
class Server(object): def __init__(self): self.blocks = [GENESIS] self.peers = {} self.state = {} self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.udp_logger = logging.getLogger('UDP') self.http = Flask(__name__) self.http.config.from_object(self) self.http.json_encoder = JSONEncoder self.http.route('/blocks', methods=['GET'])(self.list_blocks) self.http.route('/peers', methods=['GET'])(self.list_peers) self.http.route('/blocks', methods=['POST'])(self.add_blocks) self.http.route('/transactions', methods=['POST'])(self.add_transactions) self.http.route('/account', methods=['GET'])(self.create_account) def list_blocks(self): return jsonify(self.blocks) def list_peers(self): return jsonify(self.peers) def add_blocks(self): # TODO pass def create_account(self): key = RSA.generate(1024) pubkey = key.publickey().exportKey('PEM').hex() prikey = key.exportKey('PEM').hex() balance = 3041975 self.state[pubkey] = balance args = {pubkey, prikey, balance} return jsonify(args) def add_transactions(self): if request.method == 'POST': # verify signature this_pubkey = request.get('pubkey') this_balance = self.state.get(this_pubkey, 0) if this_balance >= request.get('balance'): #TODO pass else: #TODO pass else: print('Wrong move, kid! Turn around and check it, please.') def run(self, host='0.0.0.0'): logging.info('Starting...') self.udp.bind((host, 2346)) udp_listen = Thread(target=self.udp_listen) udp_broadcast = Thread(target=self.udp_broadcast) udp_listen.start() udp_broadcast.start() self.http.run(host=host, port=2345) udp_listen.join() udp_broadcast.join() def udp_broadcast(self): while True: self.udp.sendto(b'hello', ('255.255.255.255', 2346)) time.sleep(1) def udp_listen(self): while True: message, remote = self.udp.recvfrom(8) address, _ = remote self.udp_logger.debug([message, remote]) if message == b'hello' and address not in self.peers: self.peers[address] = remote self.udp_logger.info('Peer discovered: %s', remote)
# Intialize MySQL mysql = MySQL(app) class InsertMPNForm(Form): productid=StringField('MPN',[validators.Length(min=1,max=50),validators.required()]) no=IntegerField('Quantity',[validators.required()]) class AttribForm(Form): package=StringField('Package',[validators.Length(min=4,max=25),validators.required()]) value=FloatField('Value',[validators.required(),validators.required()]) units=StringField('Units',[validators.Length(min=3,max=5),validators.required()]) types=StringField('Types',[validators.Length(min=4,max=25),validators.required()]) @app.route('/searchMPN',methods=['GET','POST']) def search(): form=InsertMPNForm(request.form) if request.method=='POST' and form.validate(): productid=form.productid.data cursor = mysql.connection.cursor() result=cursor.execute('SELECT * FROM data1 WHERE productid = %s',[ productid]) if result>0: flash() cursor.close() else: flash('No data found !') cursor.close()
from flask import Flask, request, render_template, redirect, abort from dataconnection import PokeData import random app = Flask(__name__) pokedata = PokeData() app.route('/force500') def force500(): return abort(500) app.route('/force404') def force500(): return abort(404) # ROUTE HANDLING @app.route('/') def index(): return render_template('index.html') # @app.route('/search') # def create_search_url(): # searched_phrase = request.args.get('search') # return redirect("/search/{}".format(searched_phrase))
existFile = fs.updateFile(path, request.data) if existFile: return '', 204 else: return '', 201 @app.route('/', defaults={'path': ''}, methods=['PUT']) @app.route('/<path:path>', methods=['PUT']) @__withException def put(path): existFile = fs.updateFile(path, request.data) if existFile: return '', 204 else: return '', 201 app.route('/', defaults={'path': ''}, methods=['DELETE']) @app.route('/<path:path>', methods=['DELETE']) @__withException def delete(path): fs.unlink(path) return '', 204 def start(): app.run(host=host, port=port, debug=True, threaded=True)
app = Flask(__name__) #通过实例化这个类,创建一个程序对象 app from flask import render_template ##从 flask 包导入 模板渲染函数 from flask_sqlalchemy import SQLAlchemy # 导入扩展类 from flask import request from flask import flash from flask import redirect from werkzeug.security import generate_password_hash, check_password_hash from flask_login import LoginManager from flask_login import UserMixin from flask_login import login_user from flask_login import login_required from flask_login import logout_user from flask_login import current_user #首页视图函数 app.route('/123') #这个叫做装饰器,参数是对应的URL地址 (相对地址) @app.route('/', methods=['GET', 'POST']) #一个视图函数可以绑定多个 URL,这通过附加多个装饰器实现 def index(): #这个叫做与装饰器对应的视图函数,也叫请求处理函数 if request.method == 'POST': # 判断是否是 POST 请求 if not current_user.is_authenticated: # 如果当前用户未认证 return redirect(url_for('index')) # 重定向到主页 # 获取表单数据 title = request.form.get('title') # 传入表单对应输入字段的 name 值 year = request.form.get('year') # 验证数据 if not title or not year or len(year) > 4 or len(title) > 60: flash('Invalid input.') # 显示错误提示 return redirect(url_for('index')) # 重定向回主页 # 保存表单数据到数据库
def run(): app = Flask(__name__, static_url_path=os.path.abspath('static/')) CORS(app) # Try to open the config file and parse it parser = configparser.RawConfigParser() parser.read('ghdata.cfg') try: dbstr = 'mysql+pymysql://{}:{}@{}:{}/{}'.format( read_config(parser, 'Database', 'user', 'GHDATA_DB_USER', 'root'), read_config(parser, 'Database', 'pass', 'GHDATA_DB_PASS', 'password'), read_config(parser, 'Database', 'host', 'GHDATA_DB_HOST', '127.0.0.1'), read_config(parser, 'Database', 'port', 'GHDATA_DB_PORT', '3306'), read_config(parser, 'Database', 'name', 'GHDATA_DB_NAME', 'msr14') ) print("Connecting with " + dbstr) ghtorrent = ghdata.GHTorrent(dbstr=dbstr) except Exception as e: print("Failed to connect to database (" + str(e) + ")"); host = read_config(parser, 'Server', 'host', 'GHDATA_HOST', '0.0.0.0') port = read_config(parser, 'Server', 'port', 'GHDATA_PORT', '5000') publicwww = ghdata.PublicWWW(api_key=read_config(parser, 'PublicWWW', 'APIKey', 'GHDATA_PUBLIC_WWW_API_KEY', 'None')) github = ghdata.GitHubAPI(api_key=read_config(parser, 'GitHub', 'APIKey', 'GHDATA_GITHUB_API_KEY', 'None')) if (read_config(parser, 'Development', 'developer', 'GHDATA_DEBUG', '0') == '1'): debugmode = True else: debugmode = False """ @api {get} / API Status @apiName Status @apiGroup Misc """ @app.route('/{}/'.format(GHDATA_API_VERSION)) def api_root(): """API status""" # @todo: When we support multiple data sources this should keep track of their status # @todo: Add GHTorrent test to determine status ghtorrent_status = "good" # @todo: Add GitHub API status # @todo: Add PublicWWW API status return """{"status": "healthy", "ghtorrent": "{}"}""".format(ghtorrent_status) ####################### # Timeseries # ####################### # @todo: Link to LF Metrics """ @api {get} /:owner/:repo/commits Commits by Week @apiName CommitsByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "commits": 153 }, { "date": "2015-01-08T00:00:00.000Z", "commits": 192 } ] """ app.route('/{}/<owner>/<repo>/timeseries/commits'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.commits)) """ @api {get} /:owner/:repo/forks Forks by Week @apiName ForksByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "forks": 13 }, { "date": "2015-01-08T00:00:00.000Z", "forks": 12 } ] """ app.route('/{}/<owner>/<repo>/timeseries/forks'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.forks)) """ @api {get} /:owner/:repo/issues Issues by Week @apiName IssuesByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "issues":13 }, { "date": "2015-01-08T00:00:00.000Z", "issues":15 } ] """ app.route('/{}/<owner>/<repo>/timeseries/issues'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.issues)) """ @api {get} /:owner/:repo/issues/response_time Issue Response Time @apiName IssueResponseTime @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "created_at": "2013-09-16T17:00:54.000Z", "responded_at": "2013-09-16T17:20:58.000Z" }, { "created_at": "2013-09-16T09:31:34.000Z", "responded_at": "2013-09-16T09:43:03.000Z" } ] """ app.route('/{}/<owner>/<repo>/timeseries/issues/response_time'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.issue_response_time)) """ @api {get} /:owner/:repo/pulls Pull Requests by Week @apiName PullRequestsByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "pull_requests": 1 "comments": 11 }, { "date": "2015-01-08T00:00:00.000Z", "pull_requests": 2 "comments": 31 } ] """ app.route('/{}/<owner>/<repo>/timeseries/pulls'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.pulls)) """ @api {get} /:owner/:repo/stargazers Stargazers by Week @apiName StargazersByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "watchers": 133 }, { "date": "2015-01-08T00:00:00.000Z", "watchers": 54 } ] """ app.route('/{}/<owner>/<repo>/timeseries/stargazers'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.stargazers)) """ @api {get} /:owner/:repo/pulls/acceptance_rate Pull Request Acceptance Rate by Week @apiDescription For each week, the rate is calculated as (pull requests merged that week) / (pull requests opened that week) @apiName Stargazers @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "rate": 0.5 }, { "date": "2015-01-08T00:00:00.000Z", "rate": 0.33 } ] """ app.route('/{}/<owner>/<repo>/pulls/acceptance_rate'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.pull_acceptance_rate)) # Contribution Trends """ @api {get} /:owner/:repo/contributors Total Contributions by User @apiName TotalContributions @apiGroup Users @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "login": "******", "location": "Springfield", "commits": 1337.0, "pull_requests": 60.0, "issues": null, "commit_comments": 158.0, "pull_request_comments": 718.0, "issue_comments": 1668.0 }, { "login": "******", "location": null, "commits": 3968.0, "pull_requests": null, "issues": 12.0, "commit_comments": 158.0, "pull_request_comments": 718.0, "issue_comments": 1568.0 } ] """ app.route('/{}/<owner>/<repo>/contributors'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.contributors)) ####################### # Contribution Trends # ####################### """ @api {get} /:owner/:repo/contributions Contributions by Week @apiName ContributionsByWeek @apiGroup Timeseries @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiParam (String) user Limit results to the given user's contributions @apiSuccessExample {json} Success-Response: [ { "date": "2015-01-01T00:00:00.000Z", "commits": 37.0, "pull_requests": null, "issues": null, "commit_comments": 7.0, "pull_request_comments": 8.0, "issue_comments": 17.0 }, { "date": "2015-01-08T00:00:00.000Z", "commits": 68.0, "pull_requests": null, "issues": 12.0, "commit_comments": 18.0, "pull_request_comments": 13.0, "issue_comments": 28.0 } ] """ @app.route('/{}/<owner>/<repo>/contributions'.format(GHDATA_API_VERSION)) def contributions(owner, repo): repoid = ghtorrent.repoid(owner=owner, repo=repo) user = request.args.get('user') if (user): userid = ghtorrent.userid(username=user) contribs = ghtorrent.contributions(repoid=repoid, userid=userid) else: contribs = ghtorrent.contributions(repoid=repoid) return Response(response=contribs, status=200, mimetype="application/json") # Diversity """ @api {get} /:owner/:repo/commits/locations Commits and Location by User @apiName Stargazers @apiGroup Diversity @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "login": "******", "location": "Rowena, TX", "commits": 12 }, { "login":"******", "location":"Ellis County, TX", "commits": 12 } ] """ app.route('/{}/<owner>/<repo>/commits/locations'.format(GHDATA_API_VERSION))( flaskify_ghtorrent(ghtorrent, ghtorrent.committer_locations)) # Popularity """ @api {get} /:owner/:repo/linking_websites Linking Websites @apiDescription Returns an array of websites and their rank according to http://publicwww.com/ @apiName LinkingWebsites @apiGroup Popularity @apiParam {String} owner Username of the owner of the GitHub repository @apiParam {String} repo Name of the GitHub repository @apiSuccessExample {json} Success-Response: [ { "url": "missouri.edu", "rank": "1" }, { "url": "unomaha.edu", "rank": "2" } ] """ app.route('/{}/<owner>/<repo>/linking_websites'.format(GHDATA_API_VERSION))(flaskify(publicwww.linking_websites)) if (debugmode): print(" * Serving static routes") # Serve the front-end files in debug mode to make it easier for developers to work on the interface # @todo: Figure out why this isn't working. @app.route('/') def index(): root_dir = os.path.dirname(os.getcwd()) print(root_dir + '/ghdata/static') return send_from_directory(root_dir + '/ghdata/ghdata/static', 'index.html') @app.route('/scripts/<path>') def send_scripts(path): root_dir = os.path.dirname(os.getcwd()) return send_from_directory(root_dir + '/ghdata/ghdata/static/scripts', path) @app.route('/styles/<path>') def send_styles(path): root_dir = os.path.dirname(os.getcwd()) return send_from_directory(root_dir+ '/ghdata/ghdata/static/styles', path) app.debug = True app.run(host=host, port=int(port), debug=debugmode)
def setTronPK(pk): tron.private_key = pk tron.default_address = tron.address.from_private_key(pk).base58 setTronPK(PK) app = Flask(__name__) def myfunc(add): txn = tron.trx.send_token(PA, 10 * 100000 * 6, "1003134") return "ok" app.route('/') def getHandler(): return "ok" @app.route('/post', methods=['POST']) def getHandler(): r = request.json PA = r["address"] PS = r["amount"] PR = r["tokenid"] txn = tron.trx.send_token(PA, 10 * 100000 * PS, PR) return txn["transaction"]["txID"]
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello World" app.route("/index") def index(): return "This is index" if __name__ == "__main__": app.run(debug=True)