#!/usr/bin/python3 ''' Flask Module''' from flask import Flask app = Flask(__name__) @app.route('/', strict_slashes=False) def hello(): ''' return welcoming str ''' return 'Hello, HBNB!' @app.route('/hbnb', strict_slashes=False) def display_HBNB(): ''' returns HBNB ''' return 'HBNB' @app.route('/c/<text>', strict_slashes=False) def display_text(text=None): ''' return C and the value of the variable text ''' return 'C {}'.format(text).replace('_', ' ') if __name__ == '__main__': app.env = 'development' app.run(host='0.0.0.0', port=5000)
import json import os.path from flask import Flask, jsonify, safe_join, send_from_directory from time import sleep from random import random api = Flask(__name__) api.env = "development" api.debug = True FILES = os.path.dirname(__file__) @api.route('/', methods=['GET']) def index(): return jsonify([ { 'url': '/v2/products/{category}' }, { 'url': '/v2/availability/{manufacturer}' }, ]) @api.route('/v2/products/<category>', methods=['GET']) def products(category): if random() > 0.9: with open(safe_join(FILES, f'products-{category}.json')) as f: data = json.load(f) return jsonify(data[:5]) return send_from_directory(FILES, filename=f'products-{category}.json')
from flask import Flask, request import server.logic as logic app = Flask(__name__) app.env = "Production" @app.route("/register", methods=["POST"]) def register(): device_id = request.get_json().get("device_id") secret = logic.register_device(device_id)[str(device_id)].secret return {"registered": True, "secret": secret} @app.route("/is_registered/<device_id>", methods=["GET"]) def is_registered(device_id): if logic.get_device_info(device_id): return {"is_registered": True} return {"is_registered": False} @app.route("/get_secret/<device_id>", methods=["GET"]) def get_secret(device_id): return {"secret": logic.get_device_info(device_id=device_id).secret} @app.route("/validate/<device_id>", methods=["GET"]) def validate_otp(device_id): received_otp = request.get_json().get("OTP") if logic.validate_otp(device_id=device_id, received_otp=str(received_otp)): return {"is_valid": True}
import feedparser from flask import Flask, render_template app = Flask(__name__) ITUNE_FEEDS = { 'new-release': 'https://rss.itunes.apple.com/api/v1/us/apple-music/new-releases/all/10/explicit.rss', 'top-songs': 'https://rss.itunes.apple.com/api/v1/us/apple-music/top-songs/all/10/explicit.rss', 'top-albums': 'https://rss.itunes.apple.com/api/v1/us/apple-music/top-albums/all/10/explicit.rss' } @app.route("/<feed_type>") def get_feed(feed_type='new-release'): feed = feedparser.parse(ITUNE_FEEDS[feed_type]) return render_template("home.html", items=feed['entries']) app.env = "development" app.run(debug=True)
from flask import Flask import config from apis.v1 import blueprint as api1 config.setup_logging() SERVER = Flask(__name__) SERVER.register_blueprint(api1) if __name__ == "__main__": SERVER.env = config.DEV_ENV SERVER.run(host=config.DEV_HOST, port=config.DEV_PORT, debug=True)
def create_server(): app = Flask(__name__) app.secret_key = b'(\xe4S$\xce\xa81\x80\x8e\x83\xfa"b%\x9fr' app.env = 'development' return app
# Instantiate connection to database creds = yaml.safe_load(open("creds.yaml", "r")) dbHostUri = "mongodb+srv://" + creds["DB_USER"] + ":" + creds["DB_PASSWORD"] + \ "@cluster0-ollas.mongodb.net/test?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE" db = connect(host=dbHostUri) # Instantiate connection to AWS awsSession = boto3.Session( aws_access_key_id=creds["AWS_ACCESS_KEY"], aws_secret_access_key=creds["AWS_SECRET_KEY"] ) # Instantiate application application = Flask(__name__) application.env = application.config["ENV"] if (application.env == "production"): # Route handlers for FE @application.route("/assets/<string:requestedStaticDirectory>/<path:path>") def sendStaticComponent(requestedStaticDirectory, path): if requestedStaticDirectory not in STATIC_DIRECTORIES: return Response("Not a valid static asset directory", status=400) return send_from_directory(STATIC_ASSETS_DIRECTORY_ROOT + requestedStaticDirectory, path) @application.route("/") def index(): return send_file(STATIC_DIRECTORY_ROOT + "index.html") @application.errorhandler(404) def rerouteToIndex(e):
from flask import Flask, render_template, jsonify from flask_cors import CORS from makeSentence import makeSentence app = Flask(__name__) CORS(app) @app.route("/") def index(): return render_template("index.html", sentence=makeSentence()) @app.route("/api") def api(): return jsonify(sentence=makeSentence()) if __name__ == "__main__": app.debug = True app.env = "DEV" app.run()
from flask import Flask from routes.routes import main app = Flask(__name__, template_folder='views') app.debug = True app.env = 'Development' app.register_blueprint(main) app.run('0.0.0.0', 3000)
@app.route('/') def sensor_data(): while(1): query = "SELECT * FROM (SELECT * FROM temps_found ORDER BY\ time_stamp DESC LIMIT 20) sub ORDER BY time_stamp ASC;" cloud_mycursor.execute(query) cloud_data = cloud_mycursor.fetchall() query = "SELECT * FROM (SELECT * FROM temps_found ORDER BY\ time_stamp DESC LIMIT 200) sub ORDER BY time_stamp ASC;" edge_mycursor.execute(query) edge_data = edge_mycursor.fetchall() edge_mydb.commit() cloud_mydb.commit() time_stamps = range(0,len(cloud_data+edge_data)) print(time_stamps) cloud_data = edge_data+cloud_data return render_template("index2.html", data_cloud=cloud_data, data_edge=edge_data, timestamps=time_stamps) if(__name__ == '__main__'): app.debug = True app.env = "" app.run('0.0.0.0', port=5000)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_migrate import Migrate from config import Config from flask_marshmallow import Marshmallow app = Flask(__name__) app.env = 'production' app.config.from_object(Config) login = LoginManager(app) login.login_view = 'login' db = SQLAlchemy(app) migrate = Migrate(app, db) ma = Marshmallow(app) from app import routing, models from app.util import filters
from flask import Flask from flask_cors import CORS from flask_script import Manager import env app = Flask(__name__) CORS(app, supports_credentials=True) app.debug = env.debug app.config['SECRET_KEY'] = env.secret_key app.env = env.environment manager = Manager(app)
from powerfulseal import makeLogger from powerfulseal.policy import PolicyRunner from powerfulseal.policy.action_nodes import ActionNodes from powerfulseal.policy.action_pods import ActionPods from werkzeug.middleware.proxy_fix import ProxyFix # Flask instance and routes app = Flask(__name__, static_url_path="/static", static_folder="dist/static", template_folder="dist") CORS(app, resources={r"/api/*": {"origins": "*"}}) app.debug = False app.env = "PRODUCTION" # singleton for a minute config = dict() @app.route('/logs') def logs(): logs = config.get("logger").logs return render_template( 'logs.html.j2', logs=logs, ) @app.route('/', defaults={'path': ''})
from home import home_bp from labels.routes import labels_bp from wine.routes import wine_bp from models import (open_db_session, Sommelier) # Create Flask app app = Flask(__name__) # Register Blueprints app.register_blueprint(home_bp) app.register_blueprint(auth_bp) app.register_blueprint(labels_bp) app.register_blueprint(wine_bp) # Set Flask app configs from environment variables app.env = os.environ.get('FLASK_ENV') app.secret_key = os.environ.get('FLASK_SECRET_KEY') # Initialize LoginManager login_manager = LoginManager() login_manager.login_view = '/login' login_manager.login_message = 'Access requires logging in' login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): DBSession = open_db_session() user = DBSession.query(Sommelier).get(int(user_id)) DBSession.close() return user
def create(env=None) -> Flask: """ Create a Flask app and configure it. Set the environment by setting FLASK_ENV as environment variable (also possible in .env). Or, overwrite any FLASK_ENV setting by passing an env in directly (useful for testing for instance). """ from flexmeasures.utils.config_utils import read_config, configure_logging from flexmeasures.utils.app_utils import install_secret_key from flexmeasures.utils.error_utils import add_basic_error_handlers # Create app configure_logging( ) # do this first, see http://flask.pocoo.org/docs/dev/logging/ # we're loading dotenv files manually & early (can do Flask.run(load_dotenv=False)), # as we need to know the ENV now (for it to be recognised by Flask()). load_dotenv() app = Flask("flexmeasures") if env is not None: # overwrite app.env = env if env == "testing": app.testing = True # App configuration read_config(app) if app.debug and not app.testing and not app.cli: print(app.config) add_basic_error_handlers(app) app.mail = Mail(app) FlaskJSON(app) cors = CORS(app) # configure Redis (for redis queue) if app.testing: from fakeredis import FakeStrictRedis app.queues = dict( forecasting=Queue(connection=FakeStrictRedis(), name="forecasting"), scheduling=Queue(connection=FakeStrictRedis(), name="scheduling"), ) else: redis_conn = Redis( app.config["FLEXMEASURES_REDIS_URL"], port=app.config["FLEXMEASURES_REDIS_PORT"], db=app.config["FLEXMEASURES_REDIS_DB_NR"], password=app.config["FLEXMEASURES_REDIS_PASSWORD"], ) """ FWIW, you could use redislite like this (not on non-recent os.name=="nt" systems or PA, sadly): from redislite import Redis redis_conn = Redis("MY-DB-NAME", unix_socket_path="/tmp/my-redis.socket", ) """ app.queues = dict( forecasting=Queue(connection=redis_conn, name="forecasting"), scheduling=Queue(connection=redis_conn, name="scheduling"), ) # Some basic security measures if not app.env == "documentation": install_secret_key(app) SSLify(app) # Register database and models, including user auth security measures from flexmeasures.data import register_at as register_db_at register_db_at(app) # Register the API from flexmeasures.api import register_at as register_api_at register_api_at(app) # Register the UI from flexmeasures.ui import register_at as register_ui_at register_ui_at(app) # Profile endpoints (if needed, e.g. during development) @app.before_request def before_request(): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): g.start = time.time() @app.teardown_request def teardown_request(exception=None): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): diff = time.time() - g.start if all( [kw not in request.url for kw in ["/static", "favicon.ico"]]): app.logger.info( f"[PROFILE] {str(round(diff, 2)).rjust(6)} seconds to serve {request.url}." ) return app
# init routers routes.init(app) # default router @app.route('/') def default_route(): product_collection = db.product data = product_collection.find_one({"price": "12"}) return dumps(data) # # get products # @app.route('/products') # def get_products(): # page = req.args.get('page', 0, type=int) # limit = req.args.get('limit', 10, type=int) # product_collection = db.product # data = product_collection.find().skip(page*limit).limit(limit) # resp = res(dumps(data), status=200, mimetype='application/json') # return resp if __name__ == '__main__': load_dotenv(verbose=True) FLASK_ENV = os.getenv('FLASK_ENV') FLASK_PORT = os.getenv('FLASK_PORT') app.env = FLASK_ENV app.run(port=FLASK_PORT)
# from routes.admin import admin # from routes.api import api # from routes.users import users from flask import Flask, blueprints from routes import * from datetime import timedelta import os app = Flask(__name__) app.env = "production" app.config['SECRET_KEY'] = os.urandom(24) app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=3) app.register_blueprint(index, url_prefix='/') # app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(api, url_prefix='/api') app.register_blueprint(users, url_prefix='/users') # 修改jinja2的调用变为{[ ]} app.jinja_env.variable_start_string = '{[' app.jinja_env.variable_end_string = ']}' # @app.errorhandler(405) # def not_found(error): # print(error) # return "小伙子不要总想着搞事", 404 if __name__ == '__main__': app.run(host="0.0.0.0")
def create_app(): """Set up the application.""" flask_app = Flask(__name__.split('.')[0]) local = CONFIG_BROKER['local'] flask_app.config.from_object(__name__) flask_app.config['LOCAL'] = local flask_app.debug = CONFIG_SERVICES['debug'] flask_app.env = 'development' if CONFIG_SERVICES['debug'] else 'production' flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email'] # Future: Override config w/ environment variable, if set flask_app.config.from_envvar('BROKER_SETTINGS', silent=True) # Set parameters broker_file_path = CONFIG_BROKER['broker_files'] AccountHandler.FRONT_END = CONFIG_BROKER['full_url'] SesEmail.is_local = local if SesEmail.is_local: SesEmail.emailLog = os.path.join(broker_file_path, 'email.log') # If local, make the email directory if needed if local and not os.path.exists(broker_file_path): os.makedirs(broker_file_path) JsonResponse.debugMode = flask_app.debug if CONFIG_SERVICES['cross_origin_url'] == "*": CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id") else: CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'], allow_headers="*", expose_headers="X-Session-Id") # Enable DB session table handling flask_app.session_interface = UserSessionInterface() # Set up bcrypt bcrypt = Bcrypt(flask_app) @flask_app.teardown_appcontext def teardown_appcontext(exception): GlobalDB.close() @flask_app.before_request def before_request(): # Set global value for local g.is_local = local sess = GlobalDB.db().session # setup user g.user = None if session.get('name') is not None: g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none() # Root will point to index.html @flask_app.route("/", methods=["GET"]) def root(): return "Broker is running" @flask_app.errorhandler(ResponseException) def handle_response_exception(exception): return JsonResponse.error(exception, exception.status) @flask_app.errorhandler(Exception) def handle_exception(exception): wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception)) return JsonResponse.error(wrapped, wrapped.status) # Add routes for modules here add_login_routes(flask_app, bcrypt) add_file_routes(flask_app, local, broker_file_path) add_generation_routes(flask_app, local, broker_file_path) add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt) add_domain_routes(flask_app) add_exception_handlers(flask_app) return flask_app
# Session app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379', db=0) app.config['SESSION_COOKIE_SECURE'] = True Session(app) @app.route('/') def hello_world(): timeNow = datetime.datetime.now() if "application_name" not in session: application_name = "appTwo" + str( timeNow.strftime("%Y-%m-%d_%H-%M-%S")) session['application_name'] = application_name + "/n Session" if "application_name" in session: return session['application_name'] else: application_name = "appTwo" + str( timeNow.strftime("%Y-%m-%d_%H-%M-%S")) return application_name if __name__ == '__main__': app.secret_key = "appTwoSecretKey" app.env = "Development" app.debug = True app.run(host="127.0.0.1", port="6002")
from flask import Flask from flask_socketio import SocketIO from src.config import flask_config app = Flask(__name__) app.config['SECRET_KEY'] = flask_config['secret'] app.env = flask_config['env'] app.debug = flask_config['debug'] socket = SocketIO(app, cors_allowed_origins='*', always_connect=True)
from dotenv import dotenv_values as dotenv from flask import Flask app = Flask(__name__) app.env = dotenv().get('ENV', 'development') @app.route('/') def index(): return 'det virker' if __name__ == "__main__": app.run(debug=dotenv().get('DEBUG', True))
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) print(__name__) app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index') app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/' print('...............', app.instance_path, '.................') app.config.from_mapping(SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite')) app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/' toolbar = DebugToolbarExtension(app) # app.config["flask_profiler"] = { # "enabled": app.config["DEBUG"], # "storage": { # "engine": "sqlite" # }, # "basicAuth": { # "enabled": False, # "username": "******", # "password": "******" # }, # "ignore": [ # "^/static/.*" # ] # } if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass @app.route def test(): return "test" @app.route('/hello') def hello(): return "Hellow world" def test(): return "test" app.add_url_rule('/test', 'test', test) def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context) template_rendered.connect(log_template_renders, app) before_render_template.connect(log_template_renders, app) def request_finishing(sender): print("request finishing") print(sender) req = app.request_context print(req) def after_request(resp): print(dir(resp)) # resp = Response() # app.after_request(after_request) # app.teardown_request(request_finishing) @request_started.connect_via(app) def log_request(sender, **extra): g.rand = os.urandom(42) print("**********************", g.rand, "**********************") print(sender, 'request received..............---------==') sender.logger.debug('Request context is set up') request_started.connect(log_request, app) from . import db app.env = 'development' db.init_app(app) @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): print('Template %s is rendered with %s' % (template.name, context)) return app
from flask import Flask, render_template app = Flask(__name__) @app.route('/video') def video(): return render_template('video.html') if __name__ == '__main__': app.env = '' #app.run('127.0.0.1',port=9997, debug=True) app.run('120.27.55.146', port=9997, debug=True)
change_in_data = bot_data["changed"] message = bot_data['message'] users = set() if change_in_data == True and len(message) != 0: client_data = client.messages.list() for msg in client_data: if msg.to != 'whatsapp:+14155238886': users.add(msg.to) for msg in message: message_body += msg for user in users: client.messages.create(body=message_body,from_='whatsapp:+14155238886',to=user) logging.warning(f"Message sent to {user}") time.sleep(1) # client.messages.create(body=message_body,from_='whatsapp:+14155238886',to='whatsapp:+917004784338') # time.sleep(1) logging.warning("All Messages sent to users") time.sleep(3600 * 3) except Exception as e: logging.warning(e) if __name__ == "__main__": search_updates = threading.Thread(target=searchUpdates) search_updates.start() application.env='production' application.run(debug = True, host='0.0.0.0',port='5000',use_reloader=False) search_updates.join()
from flask import Flask from ..constants import SECRET_KEY, ENVIRONMENT app = Flask(__name__) app.secret_key = SECRET_KEY app.env = ENVIRONMENT
def create( env: Optional[str] = None, path_to_config: Optional[str] = None, plugins: Optional[List[str]] = None, ) -> Flask: """ Create a Flask app and configure it. Set the environment by setting FLASK_ENV as environment variable (also possible in .env). Or, overwrite any FLASK_ENV setting by passing an env in directly (useful for testing for instance). A path to a config file can be passed in (otherwise a config file will be searched in the home or instance directories). Also, a list of plugins can be set. Usually this works as a config setting, but this is useful for automated testing. """ from flexmeasures.utils import config_defaults from flexmeasures.utils.config_utils import read_config, configure_logging from flexmeasures.utils.app_utils import set_secret_key, init_sentry from flexmeasures.utils.error_utils import add_basic_error_handlers # Create app configure_logging( ) # do this first, see https://flask.palletsprojects.com/en/2.0.x/logging # we're loading dotenv files manually & early (can do Flask.run(load_dotenv=False)), # as we need to know the ENV now (for it to be recognised by Flask()). load_dotenv() app = Flask("flexmeasures") if env is not None: # overwrite app.env = env if app.env == "testing": app.testing = True if app.env == "development": app.debug = config_defaults.DevelopmentConfig.DEBUG # App configuration read_config(app, custom_path_to_config=path_to_config) if plugins: app.config["FLEXMEASURES_PLUGINS"] += plugins add_basic_error_handlers(app) if not app.env in ("development", "documentation") and not app.testing: init_sentry(app) app.mail = Mail(app) FlaskJSON(app) cors = CORS(app) # configure Redis (for redis queue) if app.testing: from fakeredis import FakeStrictRedis app.queues = dict( forecasting=Queue(connection=FakeStrictRedis(), name="forecasting"), scheduling=Queue(connection=FakeStrictRedis(), name="scheduling"), ) else: redis_conn = Redis( app.config["FLEXMEASURES_REDIS_URL"], port=app.config["FLEXMEASURES_REDIS_PORT"], db=app.config["FLEXMEASURES_REDIS_DB_NR"], password=app.config["FLEXMEASURES_REDIS_PASSWORD"], ) """ FWIW, you could use redislite like this (not on non-recent os.name=="nt" systems or PA, sadly): from redislite import Redis redis_conn = Redis("MY-DB-NAME", unix_socket_path="/tmp/my-redis.socket", ) """ app.queues = dict( forecasting=Queue(connection=redis_conn, name="forecasting"), scheduling=Queue(connection=redis_conn, name="scheduling"), ) # Some basic security measures set_secret_key(app) if app.config.get("SECURITY_PASSWORD_SALT", None) is None: app.config["SECURITY_PASSWORD_SALT"] = app.config["SECRET_KEY"] if not app.env in ("documentation", "development"): SSLify(app) # Register database and models, including user auth security handlers from flexmeasures.data import register_at as register_db_at register_db_at(app) # add auth policy from flexmeasures.auth import register_at as register_auth_at register_auth_at(app) # Register the CLI from flexmeasures.cli import register_at as register_cli_at register_cli_at(app) # Register the API from flexmeasures.api import register_at as register_api_at register_api_at(app) # Register plugins # If plugins register routes, they'll have precedence over standard UI # routes (first registration wins). However, we want to control "/" separately. from flexmeasures.utils.app_utils import root_dispatcher from flexmeasures.utils.plugin_utils import register_plugins app.add_url_rule("/", view_func=root_dispatcher) register_plugins(app) # Register the UI from flexmeasures.ui import register_at as register_ui_at register_ui_at(app) # Profile endpoints (if needed, e.g. during development) @app.before_request def before_request(): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): g.start = time.time() @app.teardown_request def teardown_request(exception=None): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): diff = time.time() - g.start if all( [kw not in request.url for kw in ["/static", "favicon.ico"]]): app.logger.info( f"[PROFILE] {str(round(diff, 2)).rjust(6)} seconds to serve {request.url}." ) return app
# Librairies from flask import Flask, jsonify import pymysql from dotenv import load_dotenv, find_dotenv import os # Variables load_dotenv(find_dotenv()) app = Flask(__name__) app.config['DEBUG'] = True app.env = "dev" # connection à la base de données def connection(): return pymysql.connect(host=os.getenv("DB_HOST"), user=os.getenv("DB_USER"), password=os.getenv("DB_PASS"), db=os.getenv("DB_NAME"), charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor) # Routes disponibles @app.route("/", methods=["GET"]) def home(): con = connection() with con: cur = con.cursor() sql = 'SELECT * from users' cur.execute(sql, ())
from actions import mgr_actions, user_actions, system import assists as ASST from fview_debug import debuging from view_resource import RESOURCE from view_api import API #logging.basicConfig(level=logging.DEBUG, filename='sm_server.log', filemode='w', format='(%(funcName)-10s) %(message)s') #loger = logging.getLogger() loger.debug("starting server now...") # 初始化Flask app = Flask(__name__) #app.config.from_object(cur_config.fconf) app.secret_key = os.environ.get('SECRET_KEY') or 'zxf***YFJEU7#@#1HFEiefj' app.env = cur_config.conf_server('mode') myschool.settoken(cur_config.school_token) print('myschool.token.done') @app.route("/system", methods=["GET", "POST"]) def back_system(): # 超级后台 # 管理操作: # 已注册的学校列表 rtdata = { 'success': 'yes', 'msg': 'done', 'code': 0, 'data': None, 'dlen': 0
from flask import Flask from url import GetUrls APP = Flask(__name__) APP.env = 'development' APP.testing = True GetUrls.fetch_urls(APP) if __name__ == '__main__': APP.run(debug=True)
def create_app(): """Set up the application.""" flask_app = Flask(__name__.split('.')[0]) local = CONFIG_BROKER['local'] flask_app.config.from_object(__name__) flask_app.config['LOCAL'] = local flask_app.debug = CONFIG_SERVICES['debug'] flask_app.env = 'development' if CONFIG_SERVICES['debug'] else 'production' flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email'] # Make the app not care if there's a trailing slash or not flask_app.url_map.strict_slashes = False # Future: Override config w/ environment variable, if set flask_app.config.from_envvar('BROKER_SETTINGS', silent=True) # Set parameters broker_file_path = CONFIG_BROKER['broker_files'] AccountHandler.FRONT_END = CONFIG_BROKER['full_url'] SesEmail.is_local = local if SesEmail.is_local: SesEmail.emailLog = os.path.join(broker_file_path, 'email.log') # If local, make the email directory if needed if local and not os.path.exists(broker_file_path): os.makedirs(broker_file_path) JsonResponse.debugMode = flask_app.debug if CONFIG_SERVICES['cross_origin_url'] == "*": CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id") else: CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'], allow_headers="*", expose_headers="X-Session-Id") # Enable DB session table handling flask_app.session_interface = UserSessionInterface() # Set up bcrypt bcrypt = Bcrypt(flask_app) @flask_app.teardown_appcontext def teardown_appcontext(exception): GlobalDB.close() @flask_app.before_request def before_request(): # Set global value for local g.is_local = local sess = GlobalDB.db().session # setup user g.user = None if session.get('name') is not None: g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none() content_type = request.headers.get('Content-Type') # If the request is a POST we want to log the request body if request.method == 'POST' and content_type and 'login' not in request.url.lower(): request_body = {} # If request is json, turn it into a dict if 'application/json' in content_type: request_body = json.loads(request.get_data().decode('utf8')) elif 'multipart/form-data' in content_type: # If request is a multipart request, get only the form portions of it for key in request.form.keys(): request_body[key] = request.form[key] request_dict = { 'message': 'Request body for ' + request.url, 'body': request_body } logger.info(request_dict) # Root will point to index.html @flask_app.route("/", methods=["GET"]) def root(): return "Broker is running" @flask_app.errorhandler(ResponseException) def handle_response_exception(exception): return JsonResponse.error(exception, exception.status) @flask_app.errorhandler(Exception) def handle_exception(exception): wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception)) return JsonResponse.error(wrapped, wrapped.status) # Add routes for modules here add_login_routes(flask_app, bcrypt) add_file_routes(flask_app, local, broker_file_path) add_generation_routes(flask_app, local, broker_file_path) add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt) add_dashboard_routes(flask_app) add_settings_routes(flask_app) add_domain_routes(flask_app) add_exception_handlers(flask_app) return flask_app
return redirect(url_for('your_snapshots')) @app.route('/upload', methods=['POST']) @authenticated def upload(): """Upload a photo""" return redirect(url_for('snapshot')) @app.route('/snapshot', methods=['GET']) @authenticated def snapshot(): """Your snapshot""" # TODO: Add upload call to snappy return render_template('snapshot.html') @app.route('/logout', methods=['GET']) def logout(): """Log the user out""" session['snapshots_email'] = None return redirect(url_for('main')) if __name__ == '__main__': app.debug = settings.DEBUG app.env = 'dev' port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
name = code simpl_buf = request.args.get('simpl_buf') simpl_dp = request.args.get('simpl_dp') if code != None and wkt != None : expression = "ST_SetSRID(ST_Multi(ST_GeomFromText('%s')), 4326)" % wkt Region(name = name, code = code, expression = expression, simpl_buf = simpl_buf, simpl_dp = simpl_dp).add() DBSession.commit() region = Region.filter_by(code=code).one() return flask.jsonify({ 'id': region.id, 'result': 'created' }) else: return flask.jsonify({ 'result': 'failed', 'error': 'not_enough_arguments', 'errorMsg': 'You need to specify code and wkt or geo_json at least' }), 500 if __name__ == '__main__': from osmshp import Env app.env = Env() app.run(host='0.0.0.0', debug=True)