Beispiel #1
1
 def setUp(self):
     app = Flask("tests", static_url_path="/static")
     app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test_idb.db"
     db.init_app(app)
     db.app = app
     db.configure_mappers()
     db.create_all()
def create_app(config_file):

    application = Flask(__name__)
    application.config.from_pyfile(config_file)
    db.init_app(application)
    api = Api(application)

    from athlete_api import AthletesAPI, AthletesListAPI
    from athlete_stats_api import StrongestAthletesAPI

    from team_api import TeamsListAPI

    api.add_resource(AthletesListAPI, '/api/athletes', endpoint='athletes_list')
    api.add_resource(AthletesAPI, '/api/athletes/<int:id>', endpoint='athletes')

    api.add_resource(StrongestAthletesAPI, '/api/athletes/stats/strongest',
                                                endpoint='strongest_athletes')

    api.add_resource(TeamsListAPI, '/api/teams', endpoint='teams_list')

    @application.route('/')
    def welcome():
        return 'Welcome to Taurenk\'s CrossfitProject API'


    @application.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    return application
def create_app(config_file):
    from models import db
    import models
    app = Flask(__name__)
    app.config.from_object(config_file)
    app.url_map.default_subdomain = "media"
    app.register_blueprint(media)
    app.register_blueprint(api_home)
    app.register_blueprint(api_1_0)
    db.init_app(app)

    admin = Admin(app, name='TheMetaCity Media')
    admin.add_view(ModelView(models.MediaItem, db.session, 'Media Items'))
    admin.add_view(ModelView(models.VideoFile, db.session, 'Video Files'))
    admin.add_view(ModelView(models.VideoTrack, db.session, 'Video Tracks'))
    admin.add_view(ModelView(models.Video, db.session, 'Video'))
    admin.add_view(ModelView(models.AudioFile, db.session, 'Audio Files'))
    admin.add_view(ModelView(models.AudioTrack, db.session, 'Audio Tracks'))
    admin.add_view(ModelView(models.Audio, db.session, 'Audio'))
    admin.add_view(ModelView(models.Picture, db.session, 'Pictures'))
    admin.add_view(ModelView(models.Tags, db.session, 'Tags'))
    admin.add_view(ModelView(models.Code, db.session, 'Code'))
    admin.add_view(ModelView(models.Postcards, db.session, 'Postcards'))
    admin.add_view(ModelView(models.Licence, db.session, 'Licences'))

    return app
Beispiel #4
0
def create_app():
    app = Flask(__name__)
    app.secret_key = 'super~~~~~~~~~~~~'

    # url
    app.register_blueprint(welcome_page)
    app.register_blueprint(auth_page)

    # db
    if socket.gethostname() == 'lihaichuangdeMac-mini.local':
        print(1)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://sctlee:[email protected]:3306/singledog'
    else:
        print(2)
        conn_string = 'mysql+pymysql://%s:%s@%s:%s/%s' % (os.getenv('MYSQL_USERNAME'), os.getenv('MYSQL_PASSWORD'),\
                      os.getenv('MYSQL_PORT_3306_TCP_ADDR'), os.getenv('MYSQL_PORT_3306_TCP_PORT'),\
                      os.getenv('MYSQL_INSTANCE_NAME'))
        print(conn_string)
        app.config['SQLALCHEMY_DATABASE_URI'] = conn_string

    db.init_app(app)

    from models import User
    db.create_all(app=app)

    # login manager
    login_manager.init_app(app)

    @app.before_request
    def before_request():
        g.user = current_user

    return app
Beispiel #5
0
def create_app():
    from colorama import init
    init()
    from config import add_configs
    app = add_configs(Flask(__name__))

    from sqlalchemy_utils.functions import database_exists, create_database
    if not database_exists(app.config.get('SQLALCHEMY_DATABASE_URI')):
        create_database(app.config.get('SQLALCHEMY_DATABASE_URI'), encoding='utf8')

    with app.app_context():
        from models import db

        db.init_app(app)
        app.db = db

        from models.oauth2 import oauth2_provider
        oauth2_provider.init_app(app)

        # import models
        Migrate(app, db, directory='bin/migrations/')

        mgr = Manager(app)
        mgr.add_command('db', MigrateCommand)

    return mgr
Beispiel #6
0
Datei: main.py Projekt: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

    app.debug = app.config['DEBUG']
    app.secret_key = app.config['SECRET_KEY']

    # init flask extensions
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    app.context_processor(inject_roles)

    # init my modules
    upload.init_app(app)
    filters.init_app(app)
    views.init_app(app)

    # register routes
    app.register_blueprint(views.bp_basic)
    app.register_blueprint(views.bp_responsable)
    app.register_blueprint(views.bp_activite)
    app.register_blueprint(views.bp_brn)

    return app
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    # Load config and logging
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(
        app.config['SAMPLE_APPLICATION_LOGGING']
    )

    # Register extensions
    api = Api(app)
    Discoverer(app)
    db.init_app(app)

    api.add_resource(UnixTime, '/time')
    api.add_resource(PrintArg, '/print/<string:arg>')
    api.add_resource(ExampleApiUsage, '/search')

    return app
def create_app():
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    Consul(app)

    load_config(app)

    logging.config.dictConfig(
        app.config['GRAPHICS_LOGGING']
    )

    api = Api(app)
    api.add_resource(Graphics, '/<string:bibcode>')

    db.init_app(app)

    Discoverer(app)

    return app
Beispiel #9
0
def create_app():
    from config import add_configs
    # Register configurations
    application = add_configs(Flask(__name__))

    with application.app_context():
        # Register database (SQLAlchemy)
        from models import db
        db.init_app(application)
        application.db = db
        """
        @:type SQLAlchemy
        """

        # Register OAuth2
        from models.oauth2 import oauth2_provider
        oauth2_provider.init_app(application)

        # Register BluePrints
        from controllers import add_blueprints
        add_blueprints(application)

        # Register Api
        from controllers import add_apis
        from flask_restful import Api
        add_apis(Api(application))

    return application
Beispiel #10
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = 'this is a secret'
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    app.before_request(before_request)
    app.after_request(after_request)
    app.context_processor(context_processor)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    db.init_app(app)
    with app.app_context():
        init_all()
    app.register_blueprint(admin_app, url_prefix='/admin')
    app.register_blueprint(campaign_app, url_prefix='/')
    app.register_blueprint(character_app, url_prefix='/character')
    app.register_blueprint(dm_app, url_prefix='/dm')
    app.register_blueprint(chat_app, url_prefix='/chat')
    app.register_blueprint(items_app, url_prefix='/item-type')
    app.register_blueprint(knowledge_app, url_prefix='/knowledge')

    return app
Beispiel #11
0
def create_app():
    application = Flask(__name__)
    application.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
    # application.config['BABEL_DEFAULT_LOCALE'] = 'ru-ru'
    application.config['SECRET_KEY'] = SECRET_KEY
    application.permanent_session_lifetime = timedelta(minutes=30)

    Triangle(application)
    assets.init_app(application)
    api.init_app(application)
    api.application = application
    db.init_app(application)
    admin.init_app(application)
    login_manager.init_app(application)
    application.db = db
    application.api = api

    babel = Babel(application)
    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(["ru"])

    init_logging(application)

    return application
Beispiel #12
0
def create_app(config_name):
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login'

    if not app.debug:
        import logging
        from logging import FileHandler, Formatter

        file_handler = FileHandler(Constant.LOG_DIR, encoding='utf8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(Formatter(
            '[%(asctime)s] %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    patch_request_class(app, size=16*1024*1024) # 16MB
    configure_uploads(app, resource_uploader)

    return app
def create_app(config_file):

    application = Flask(__name__)
    application.config.from_pyfile(config_file)

    from models import db, Task, User
    from auth import auth_api, login_manager
    from task_api import TaskListApi, TaskApi
    from user_api import UserApi

    db.init_app(application)
    login_manager.init_app(application)

    application.register_blueprint(auth_api, url_prefix="/api/auth")

    api = Api(application, decorators=[login_required])
    api.add_resource(TaskListApi, "/api/tasks", endpoint="tasks")
    api.add_resource(TaskApi, "/api/tasks/<int:id>", endpoint="task")
    api.add_resource(UserApi, "/api/users", endpoint="user")

    # FOR DEVELOPMENT ONLY
    @application.after_request
    def after_request(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
        response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE")
        return response

    return application
Beispiel #14
0
def create_app(config=None, environment=None):
    app = Flask(__name__)

    # TODO: Get this from a config file
    app.config["MONGODB_SETTINGS"] = {'db': "eatdb"}
    app.config[
        "SECRET_KEY"] = "\x1a\xb1\x9d\x1d\xf2\x01\xa1X\xb8g\xed\x1c\xb3\x0f+s\xbce\xf6\x92\x83'\xf2\xbc\x96\xc6\x18\x03`\xc0\x0c("
    app.config["IV"] = '\xe7\x9d\xc7\xbd\x12l\x88\xc7\xe9D\x93!\xa2B\xed\x91'
    app.config.from_pyfile('settings.cfg', silent=True)
    app.session_interface = MongoSessionInterface(**(app.config["MONGODB_SETTINGS"]))

    with app.app_context():
        from models import db
        db.init_app(app)

        login_manager = LoginManager()

        @login_manager.user_loader
        def load_user(id):
            if id in (None, 'None'):
                return None
            try:
                from models.user import User
                return User.objects(id=id).first()
            except:
                return None

        login_manager.init_app(app)

        from views import register_routes as register_views

        register_views(app)

    return app
Beispiel #15
0
def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stress.db'
	app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
	db.init_app(app)
	with app.app_context():
		db.create_all()
	return app
Beispiel #16
0
def register_database(app):
    app.config["SQLALCHEMY_DATABASE_URI"] = ""

    db.init_app(app)
    db.app = app

    # db.create_all(bind=None)
    return app
Beispiel #17
0
def create_app():
    app = flask.Flask("app")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    app.register_blueprint(api)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Beispiel #18
0
def connect_to_db(app):
    """Connect the database to our Flask app."""

    # Configure to use our PstgreSQL database
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///test'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.app = app
    db.init_app(app)
Beispiel #19
0
def create_app():
    api = Flask('api')
    api.register_blueprint(person_blueprint)
    db.init_app(api)

    with api.app_context():
        db.create_all()

    return api
def create_app():
  app = Flask(__name__)
  app.config.from_object('config')
  Bootstrap(app)
  Bower(app)
  app.extensions['bootstrap']['cdns']['jquery'] = WebCDN("//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/")
  db.init_app(app)

  return app
def create_app():
    """Create your application."""
    app = Flask(__name__)
    app.config.from_object(settings)
    app.register_module(views)
    db.app = app
    db.init_app(app)
    db.create_all()
    return app
def init_db():
    """Create database with tables defined in models. Also create demo user"""
    app = create_app()
    with app.test_request_context():
        db.init_app(app)
        db.create_all()
        # create user
        user = User(email='admin@localhost', password='******', active=True)
        db.session.add(user)
        db.session.commit()
Beispiel #23
0
    def create_app():
        app = flask.Flask("app")
        app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@127.0.0.1/clientmanager'
        db.init_app(app)
        with app.app_context():
            # Extensions like Flask-SQLAlchemy now know what the "current" app
            # is while within this block. Therefore, you can now run........
            db.create_all()

        return None
Beispiel #24
0
def create_app():
    app = Flask(__name__, template_folder='templates')
    app.debug = True
    app.secret_key = 'secret'
    app.config.update({
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///db.sqlite'
    })
    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Beispiel #25
0
def create_json_app(config):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.app_context().push()
    return app
Beispiel #26
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)

    from models import db
    db.init_app(app)

    from views import api_bp
    app.register_blueprint(api_bp, url_prefix='/api')

    return app
Beispiel #27
0
def create_app(cfg=None):
    app = Flask(__name__)
    load_config(app, cfg)
    db.init_app(app)

    app.register_blueprint(show_entries_page)
    app.register_blueprint(add_entry_page)
    app.register_blueprint(login_page)
    app.register_blueprint(logout_page)
    
    return app
Beispiel #28
0
def create_app(config):
    iq_app = Flask(__name__)
    iq_app.config.from_object(config)
    iq_app.secret_key = '1ll#%@%^LJ2sd#lj23@$^-'

    with iq_app.app_context():
        db.init_app(iq_app)
        db.create_all()

    iq_app.register_blueprint(iq_views)
    return iq_app
Beispiel #29
0
    def setUpClass(cls):
        cls.app = app
        cls.app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@localhost:5432/test_factory_boy'
        cls.app.config['SQLALCHEMY_ECHO'] = True
        db.app = cls.app

        db.init_app(cls.app)
        cls._ctx = cls.app.test_request_context()
        cls._ctx.push()
        db.drop_all()
        db.create_all()
Beispiel #30
0
    def configure_database(self):
        """
        Database configuration should be set here
        """
        #db = SQLAlchemy()
        db.init_app(self)
        with self.app_context():
            db.create_all()

        #db = SQLAlchemy(self)
        pass
Beispiel #31
0
def init_db():
    db.init_app(app)
    db.app = app
    db.create_all()
Beispiel #32
0
def create_app():

    app = Flask(__name__)

    app.secret_key = 'iashdfpi'
    app.config.update(
        SCHEDULER_API_ENABLED=True,
        SQLALCHEMY_ECHO=True,
        SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:[email protected]/flask_dev',
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        DEBUG=True,
        MAIL_SERVER='smtp.163.com',  # 邮箱服务器
        MAIL_PROT=25,  # 每种邮箱服务器都有自己的端口
        MAIL_USE_TLS=True,
        MAIL_USE_SSL=False,
        MAIL_USERNAME='******',  # 邮箱账户
        MAIL_PASSWORD='******',  # 授权码
        MAIL_DEBUG=True)
    app.config['JOBS'] = [
        {
            'id': 'job1',
            'func': '__main__:daily_fetch_data',
            # 'args': (1, 2),
            'trigger': 'cron',  # cron表示定时任务
            'hour': 20,
            'minute': 9
        },
        {
            'id': 'job2',
            'func': '__main__:interval_test',
            'trigger': 'interval',
            'seconds': 5,
        }
    ]
    mail = Mail(app)
    db.init_app(app)
    # CSRFProtect(app)
    Migrate(app, db)
    # db.drop_all()
    # db.drop_all()

    CORS(app, resources={r"/*": {"origins": "*"}})
    # cors=CORS(app,support_credentials=True,resources=r'/*')
    # cors = CORS(app,  methods=['GET', 'HEAD', 'POST', 'OPTIONS'])

    login_manager = LoginManager()  # 实例化登录管理对象
    login_manager.init_app(app)  # 初始化应用
    login_manager.login_view = '/login'  # 设置用户登录视图函数 endpoint
    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.start()

    # socketio = SocketIO(app, cors_allowed_origins='*')

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route('/')  # 首页
    @login_required  # 需要登录才能访问
    def index():
        return render_template('index.html')

    app.register_blueprint(auth.bp, url_prefix="/auth")
    app.register_blueprint(bonds.bp, url_prefix="/rule")
    app.register_blueprint(echarts.bp, url_prefix="/echarts")
    app.register_blueprint(downloadexcel.bp, url_prefix="/excel")

    return app
Beispiel #33
0
#!/usr/bin/env python

from flask import Flask
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

import config
from models import db

server = Flask(__name__)
server.debug = config.DEBUG
server.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URL
db.init_app(server)

migrate = Migrate(server, db)
manager = Manager(server)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
Beispiel #34
0
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session, exc
from sqlalchemy import create_engine, func
from flask import Flask, jsonify, render_template, url_for, abort
from flask_sqlalchemy import SQLAlchemy
import etl
import json
import requests
from models import db,Fortune500, Sector_Industry
from config import SQLALCHEMY_DATABASE_URI, apiKey

#Initializing app

app = Flask(__name__, static_url_path= "/static", static_folder="static")
db.init_app(app)
###########################
# Database Setup
###########################

app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)


@app.before_first_request
def setup():
   try:
      etl.init()
      print("Data has been successfully written to the database!")
Beispiel #35
0
def create_app(test_config=None):
  app = Flask(__name__)
  app.config.from_object('config')
  db.init_app(app)
  CORS(app)
  
  @app.after_request
  def after_request(response):
      response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')
      response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
      return response
  #if used more then once, i defined them beforehand
  def start(request):
      page = request.args.get('page', 1, type=int)
      start = (page-1) * 10
      return start

  def allcategories():
      allcategories={category.id: category.type for category in Category.query.all()}
      return allcategories
        
  @app.route('/categories')
  def categories():
      try:
          return jsonify({
          'success': True,
          'categories': allcategories(),
          })
      except:
          abort(422)

  @app.route('/questions')
  def questions():
      try:
          return jsonify({
              'success': True,
              'questions': [question.format() for question in Question.query.offset(start(request)).limit(10)],
              'total_questions': len(Question.query.all()),
              'categories': allcategories(),
              'current_category': None
              })
      except:
          abort(422)

  @app.route('/questions/<int:question_id>', methods=['DELETE'])
  def delete(question_id):
      question = Question.query.filter(Question.id == question_id).scalar()
      if question is None:
          abort(404)
      try:
          question.delete()
          return jsonify({
          'success': True,
          })
      except:
          abort(422)

  @app.route('/questions', methods=['POST'])
  def create():
      Front = request.json
      question = Front['question']
      answer = Front['answer']
      # chehcking here question and answer is enough. because categories is there by an another method via frontend
      if len(question)>0 and len(answer)>0 :
          difficulty = Front['difficulty']
          category = Front['category']
      else:
          abort(400)        
      try:
          db.session.add(Question(
              question=question,
              answer=answer,
              difficulty=difficulty,
              category=category,
              ))
          db.session.commit()
          db.session.close()
          return jsonify({
              'success': True,
              })
      except:
          abort(422)
              
  @app.route('/questions/search', methods=['POST'])
  def search():
      Front = request.json
      SearchTerm =Front['searchTerm']
      if SearchTerm is None:
          abort(400)
      questions = [question.format() for question in Question.query.filter(Question.question.ilike(f'%{SearchTerm}%')).all()]
      try:
          return jsonify({
          'success': True,
          'questions': questions,
          'total_questions': len(questions)
          })
      except:
        abort(422)
      
 
  @app.route('/categories/<int:category_id>/questions', methods=['GET'])
  def getcategory(category_id):
    categoryGiven = Category.query.filter(Category.id == category_id).one_or_none()
    if categoryGiven is None:
        abort(404)
    try:
        questions=[question.format() for question in Question.query.filter(Question.category == category_id).offset(start(request)).limit(10)]
        return jsonify({
            'success': True,
            'questions': questions,
            'current_category': Category.query.get(category_id).format(),
            'total_questions': len(questions)
        })
    except:
        abort(422)

  @app.route('/quiz', methods=['POST'])
  def quiz():
      Front = request.json
      category = Front['quiz_category']
      pre = Front['previous_questions']
      #for the sake of testing 500 at least once :lets assume a case ; if categories dont load it should be a an internal sever here.
      if category is None:
          abort(500)
      question = None
      if category != 0:
          questions = Question.query.filter(Question.id.notin_(pre), Question.category == category).order_by(func.random()).all()
      else:
          questions = Question.query.filter(Question.id.notin_(pre)).order_by(func.random()).all()
      if len(questions)>0:
          question = questions[0].format()
      try:
          return jsonify({
              'success': True,
              'question': question
              })
      except:
        abort(422)
  
  @app.errorhandler(404)
  def notfound(error):
      return jsonify({
          'success': False,
          'error': 404,
          'message': 'not found'
      }), 404

  @app.errorhandler(422)
  def unprocessable(error):
      return jsonify({
          'success': False,
          'error': 422,
          'message': 'unprocessable'
      }), 422

  @app.errorhandler(400)
  def bad_request(error):
    return jsonify({
      "success": False, 
      "error": 400,
      "message": "bad request"
      }), 400

  @app.errorhandler(500)
  def server(error):
    return jsonify({
      "success": False, 
      "error": 500,
      "message": "internal server error"
      }), 500

  return app
Beispiel #36
0
"""
app.py
- provides the endpoints for consuming and producing
  the web app
"""

import requests
from flask import Flask, render_template, request, jsonify, session
from models import Activity, User, UserActivity, db
from sqlalchemy import exc
from flask_session import Session

# Intialises the app
web_app = Flask(__name__)
web_app.config.from_object('config.BaseConfig')
db.init_app(web_app)
Session(web_app)
BASE_URL = 'https://www.boredapi.com/api/activity'

@web_app.route("/")
def index():
    """ Home page """
    try:
        # Sets title and subtitle to be used on the page
        title = "Bored?"
        subtitle = "Find things to kill your boredom!"
        if session.get('temp_activity_id'):
            # If there was an activity id in storage, get this specific one
            # (e.g. finding one, then having to log in will keep the activity first seen)
            temp_activity_id = session['temp_activity_id']
            session.pop('temp_activity_id', None)
Beispiel #37
0
def create_app():
    """Factory to create the Flask application with cfg and db."""
    app = Flask(__name__)
    load_config(app.config)
    db.init_app(app)
    return app
Beispiel #38
0
from flask import Flask
from models import db

votr = Flask(__name__)

#load config form teh config file we created earlier
votr.config.from_object('config')

#initialize and create the database
db.init_app(votr)
db.create_all(app=votr)


@votr.route('/')
def home():
    return 'hello world'


@votr.route('/it')
def run_home():
    return 'wudup homie'


if __name__ == '__main__':
    votr.run()
Beispiel #39
0
def create_app():
    app = Flask(__name__,
                instance_relative_config=True,
                template_folder="templates",
                static_url_path="")

    app.config.from_pyfile("default.py")
    app.config.from_envvar("APP_CONFIG_FILE", silent=True)

    heroku = Heroku()
    heroku.init_app(app)

    db.init_app(app)

    migrate = Migrate(compare_type=True)
    migrate.init_app(app, db)

    admin = Admin(app)
    admin.add_view(AdminModelView(Event, db.session))
    admin.add_link(MenuLink(name="Website", endpoint="index"))
    admin.add_link(MenuLink(name="Login", url="/login"))
    admin.add_link(MenuLink(name="Logout", url='/logout'))

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    @app.context_processor
    def inject_now():
        return {'now': datetime.utcnow()}

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    get_url=url_for,
                    h=helpers)

    @app.before_first_request
    def create_user():
        role = user_datastore.find_or_create_role("admin")
        # password = os.environ.get('ADMIN_PASSWORD')
        if not User.query.filter_by(email=ADMIN_EMAIL).first():
            user = user_datastore.create_user(email=ADMIN_EMAIL,
                                              password=ADMIN_PASSWORD)
            user_datastore.add_role_to_user(user, role)
        db.session.commit()

    @app.route('/')
    @app.route('/index')
    def index():
        events = Event.query.filter(Event.date > datetime.utcnow()).order_by(
            Event.date)
        return render_template('index.html', events=events)

    @app.route('/our_work')
    def our_work():
        current = "our_work"
        return render_template('our_work.html', current=current)

    @app.route('/signup', methods=['POST'])
    def signup():
        email = request.form.get('email')
        api_key = os.environ.get('MAILCHIMP_API_KEY')
        if not api_key or not email:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
            return redirect(url_for('index'))
        server_number = api_key[-4:]
        url = f"https://{server_number}.api.mailchimp.com/3.0/lists/{LIST_ID}/members"
        headers = {
            'content-type': 'application/json',
            'Authorization': f"Basic {api_key}"
        }
        data = {'email_address': email, 'status': 'subscribed'}
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if response.ok or response.json().get('title') == 'Member Exists':
            flash('Thanks for signing up to our newsletter!')
        else:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
        return redirect(url_for('index'))

    return app
Beispiel #40
0
def get_app():
    app = Starlette(routes=routes)
    db.init_app(app)
    return app
Beispiel #41
0
from flask import Flask, request, Response
import json
from models import Member, Message, Channel, db
from datetime import datetime, timezone
import config
import pika
import sys

flask_app = Flask(__name__)
flask_app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_CONNECTION_URI
flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
flask_app.app_context().push()
db.init_app(flask_app)
db.create_all()
db.session.add(Channel(name='general'))
db.session.commit()

# RabbitMQ declaration
creds = pika.PlainCredentials(config.rUSER, config.rPW)
conn = pika.BlockingConnection(pika.ConnectionParameters(host=config.mqHOST, port=config.mqPORT, credentials=creds, heartbeat=0))
mq_chan = conn.channel()
mq_chan.queue_declare(queue=config.rmQueue, durable=True)


@flask_app.route("/v1/channels", methods=['GET', 'POST'])
def ChannelHandler():
    if 'X-User' not in request.headers:
        return Response('Unauthorized Access', 401, mimetype='text/html')
    data = json.loads(request.headers['X-User'])
    user = find_user(data["id"])
    if request.method == 'GET':
Beispiel #42
0
from flask import Flask, render_template, request, redirect, flash, session, jsonify  #render_template으로 html파일 렌더링
from models import db
import os

from login_register import login_register

app = Flask(__name__, template_folder='templates', static_folder='static')
app.register_blueprint(login_register)

app.config["SECRET_KEY"] = "ABCD"

basedir = os.path.abspath(os.path.dirname(__file__))  # database 경로를 절대경로로 설정함
dbfile = os.path.join(basedir, 'db.sqlite')  # 데이터베이스 이름과 경로
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
app.config[
    'SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True  # 사용자에게 원하는 정보를 전달완료했을때가 TEARDOWN, 그 순간마다 COMMIT을 하도록 한다.라는 설정
#여러가지 쌓아져있던 동작들을 Commit을 해주어야 데이터베이스에 반영됨. 이러한 단위들은 트렌젝션이라고함.
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)  #초기화 후 db.app에 app으로 명시적으로 넣어줌
db.app = app
db.create_all()  # 이 명령이 있어야 생성됨. DB가


@app.route('/api')
def index():
    return jsonify({'name': 'alice', 'email': '*****@*****.**'})


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5000, debug=1)
Beispiel #43
0
def connect_to_db(app):
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql:///cultivate"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.app = app
    db.init_app(app)
Beispiel #44
0
def create_app(config_filename="config.py",
               app_name=None,
               register_blueprints=True):
    # App configuration
    app = Flask(app_name or __name__)

    env_cfg = os.getenv("CUSTOM_CONFIG", config_filename)
    app.config.from_pyfile(env_cfg)

    Bootstrap(app)

    app.jinja_env.add_extension("jinja2.ext.with_")
    app.jinja_env.add_extension("jinja2.ext.do")
    app.jinja_env.globals.update(is_admin=is_admin)
    app.jinja_env.filters["state_to_str"] = state_str

    if HAS_SENTRY:
        app.config["SENTRY_RELEASE"] = raven.fetch_git_sha(
            os.path.dirname(__file__))
        sentry = Sentry(app, dsn=app.config["SENTRY_DSN"])  # noqa: F841
        print(" * Sentry support activated")
        print(" * Sentry DSN: %s" % app.config["SENTRY_DSN"])

    if app.config["DEBUG"] is True:
        app.jinja_env.auto_reload = True
        app.logger.setLevel(logging.DEBUG)

    # Logging
    if not app.debug:
        formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s "
                                      "[in %(pathname)s:%(lineno)d]")
        file_handler = RotatingFileHandler("%s/errors_app.log" % os.getcwd(),
                                           "a", 1000000, 1)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)

    mail.init_app(app)
    migrate = Migrate(app, db)  # noqa: F841
    babel = Babel(app)  # noqa: F841
    toolbar = DebugToolbarExtension(app)  # noqa: F841

    db.init_app(app)

    # Setup Flask-Security
    security = Security(  # noqa: F841
        app,
        user_datastore,
        register_form=ExtendedRegisterForm,
        confirm_register_form=ExtendedRegisterForm)

    @FlaskSecuritySignals.password_reset.connect_via(app)
    @FlaskSecuritySignals.password_changed.connect_via(app)
    def log_password_reset(sender, user):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info",
                     "Your password has been changed !")

    @FlaskSecuritySignals.reset_password_instructions_sent.connect_via(app)
    def log_reset_password_instr(sender, user, token):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info",
                     "Password reset instructions sent.")

    git_version = ""
    gitpath = os.path.join(os.getcwd(), ".git")
    if os.path.isdir(gitpath):
        git_version = subprocess.check_output(
            ["git", "rev-parse", "--short", "HEAD"])
        if git_version:
            git_version = git_version.strip().decode("UTF-8")

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(["fr", "en"])

    @babel.timezoneselector
    def get_timezone():
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.timezone

    @app.before_request
    def before_request():
        cfg = {
            "CAMGEAR_VERSION_VER": VERSION,
            "CAMGEAR_VERSION_GIT": git_version,
            "CAMGEAR_VERSION": "{0} ({1})".format(VERSION, git_version),
        }
        g.cfg = cfg

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    pictures = UploadSet("pictures", IMAGES)
    configure_uploads(app, pictures)
    patch_request_class(app, 10 * 1024 * 1024)  # 10m limit

    thumb = Thumbnail(app)  # noqa: F841

    if register_blueprints:
        from controllers.main import bp_main

        app.register_blueprint(bp_main)

        from controllers.users import bp_users

        app.register_blueprint(bp_users)

        from controllers.admin import bp_admin

        app.register_blueprint(bp_admin)

        from controllers.accessories import bp_accessories

        app.register_blueprint(bp_accessories)

        from controllers.cameras import bp_cameras

        app.register_blueprint(bp_cameras)

        from controllers.lenses import bp_lenses

        app.register_blueprint(bp_lenses)

        from controllers.autocompletion import bp_autocomplete

        app.register_blueprint(bp_autocomplete)

    @app.route("/uploads/<string:thing>/<path:stuff>", methods=["GET"])
    def get_uploads_stuff(thing, stuff):
        if app.debug:
            directory = safe_join(app.config["UPLOADS_DEFAULT_DEST"], thing)
            app.logger.debug(f"serving {stuff} from {directory}")
            return send_from_directory(directory, stuff, as_attachment=True)
        else:
            app.logger.debug(f"X-Accel-Redirect serving {stuff}")
            resp = Response("")
            resp.headers[
                "Content-Disposition"] = f"attachment; filename={stuff}"
            resp.headers[
                "X-Accel-Redirect"] = f"/_protected/media/tracks/{thing}/{stuff}"
            return resp

    @app.errorhandler(404)
    def page_not_found(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 404,
            "message": gettext("Page not found"),
            "e": msg,
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 404

    @app.errorhandler(403)
    def err_forbidden(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 403,
            "message": gettext("Access forbidden"),
            "e": msg,
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 403

    @app.errorhandler(410)
    def err_gone(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 410,
            "message": gettext("Gone"),
            "e": msg
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 410

    if not app.debug:

        @app.errorhandler(500)
        def err_failed(msg):
            pcfg = {
                "title": gettext("Whoops, something failed."),
                "error": 500,
                "message": gettext("Something is broken"),
                "e": msg,
            }
            return render_template("error_page.jinja2", pcfg=pcfg), 500

    @app.after_request
    def set_x_powered_by(response):
        response.headers["X-Powered-By"] = "camgear"
        return response

    # Other commands
    @app.cli.command()
    def routes():
        """Dump all routes of defined app"""
        table = texttable.Texttable()
        table.set_deco(texttable.Texttable().HEADER)
        table.set_cols_dtype(["t", "t", "t"])
        table.set_cols_align(["l", "l", "l"])
        table.set_cols_width([50, 30, 80])

        table.add_rows([["Prefix", "Verb", "URI Pattern"]])

        for rule in sorted(app.url_map.iter_rules(), key=lambda x: str(x)):
            methods = ",".join(rule.methods)
            table.add_row([rule.endpoint, methods, rule])

        print(table.draw())

    @app.cli.command()
    def config():
        """Dump config"""
        pp(app.config)

    @app.cli.command()
    def seed():
        """Seed database with default content"""
        make_db_seed(db)

    @app.cli.command()
    def createuser():
        """Create an user"""
        username = click.prompt("Username", type=str)
        email = click.prompt("Email", type=str)
        password = click.prompt("Password",
                                type=str,
                                hide_input=True,
                                confirmation_prompt=True)
        while True:
            role = click.prompt("Role [admin/user]", type=str)
            if role == "admin" or role == "user":
                break

        if click.confirm("Do you want to continue ?"):
            role = Role.query.filter(Role.name == role).first()
            if not role:
                raise click.UsageError("Roles not present in database")
            u = user_datastore.create_user(name=username,
                                           email=email,
                                           password=hash_password(password),
                                           roles=[role])

            db.session.commit()

            if FSConfirmable.requires_confirmation(u):
                FSConfirmable.send_confirmation_instructions(u)
                print("Look at your emails for validation instructions.")

    return app
Beispiel #45
0
def create_app(config_filename="config.development.Config", app_name=None, register_blueprints=True):
    # App configuration
    app = Flask(app_name or __name__)
    app_settings = os.getenv("APP_SETTINGS", config_filename)
    print(f" * Loading config: '{app_settings}'")
    try:
        cfg = import_string(app_settings)()
    except ImportError:
        print(" *** Cannot import config ***")
        cfg = import_string("config.config.BaseConfig")
        print(" *** Default config loaded, expect problems ***")
    if hasattr(cfg, "post_load"):
        print(" *** Doing some magic")
        cfg.post_load()
    app.config.from_object(cfg)

    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

    Bootstrap(app)

    app.jinja_env.add_extension("jinja2.ext.with_")
    app.jinja_env.add_extension("jinja2.ext.do")
    app.jinja_env.globals.update(is_admin=is_admin)

    if HAS_SENTRY:
        sentry_sdk.init(
            app.config["SENTRY_DSN"],
            integrations=[SentryFlaskIntegration(), SentryCeleryIntegration()],
            release=f"{VERSION} ({GIT_VERSION})",
        )
        print(" * Sentry Flask/Celery support activated")
        print(" * Sentry DSN: %s" % app.config["SENTRY_DSN"])

    if app.debug:
        app.jinja_env.auto_reload = True
        logging.basicConfig(level=logging.DEBUG)

    # Logging
    if not app.debug:
        formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]")
        file_handler = RotatingFileHandler("%s/errors_app.log" % os.getcwd(), "a", 1000000, 1)
        file_handler.setLevel(logging.INFO)
        file_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)

    dbLogger = logging.getLogger("reel2bits.sqltime")
    dbLogger.setLevel(logging.DEBUG)

    CORS(app, origins=["*"])

    if app.debug:
        logging.getLogger("flask_cors.extension").level = logging.DEBUG

    mail = Mail(app)  # noqa: F841
    migrate = Migrate(app, db)  # noqa: F841 lgtm [py/unused-local-variable]
    babel = Babel(app)  # noqa: F841
    app.babel = babel

    template = {
        "swagger": "2.0",
        "info": {"title": "reel2bits API", "description": "API instance", "version": VERSION},
        "host": app.config["AP_DOMAIN"],
        "basePath": "/",
        "schemes": ["https"],
        "securityDefinitions": {
            "OAuth2": {
                "type": "oauth2",
                "flows": {
                    "authorizationCode": {
                        "authorizationUrl": f"https://{app.config['AP_DOMAIN']}/oauth/authorize",
                        "tokenUrl": f"https://{app.config['AP_DOMAIN']}/oauth/token",
                        "scopes": {
                            "read": "Grants read access",
                            "write": "Grants write access",
                            "admin": "Grants admin operations",
                        },
                    }
                },
            }
        },
        "consumes": ["application/json", "application/jrd+json"],
        "produces": ["application/json", "application/jrd+json"],
    }

    db.init_app(app)

    # ActivityPub backend
    back = Reel2BitsBackend()
    ap.use_backend(back)

    # Oauth
    config_oauth(app)

    # Setup Flask-Security
    security = Security(app, user_datastore)  # noqa: F841 lgtm [py/unused-local-variable]

    @FlaskSecuritySignals.password_reset.connect_via(app)
    @FlaskSecuritySignals.password_changed.connect_via(app)
    def log_password_reset(sender, user):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info", "Your password has been changed !")

    @FlaskSecuritySignals.reset_password_instructions_sent.connect_via(app)
    def log_reset_password_instr(sender, user, token):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info", "Password reset instructions sent.")

    @FlaskSecuritySignals.user_registered.connect_via(app)
    def create_actor_for_registered_user(app, user, confirm_token):
        if not user:

            return
        actor = create_actor(user)
        actor.user = user
        actor.user_id = user.id
        db.session.add(actor)
        db.session.commit()

    @security.mail_context_processor
    def mail_ctx_proc():
        _config = Config.query.first()
        if not _config:
            print("ERROR: cannot get instance Config from database")
        instance = {"name": None, "url": None}
        if _config:
            instance["name"] = _config.app_name
        instance["url"] = app.config["REEL2BITS_URL"]
        return dict(instance=instance)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(AVAILABLE_LOCALES)

    @babel.timezoneselector
    def get_timezone():
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.timezone

    @app.before_request
    def before_request():
        _config = Config.query.first()
        if not _config:
            flash(gettext("Config not found"), "error")

        cfg = {
            "REEL2BITS_VERSION_VER": VERSION,
            "REEL2BITS_VERSION_GIT": GIT_VERSION,
            "app_name": _config.app_name,
            "app_description": _config.app_description,
        }
        if GIT_VERSION:
            cfg["REEL2BITS_VERSION"] = "{0}-{1}".format(VERSION, GIT_VERSION)
        else:
            cfg["REEL2BITS_VERSION"] = VERSION

        g.cfg = cfg

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @event.listens_for(Engine, "before_cursor_execute")
    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        if not False:
            return
        conn.info.setdefault("query_start_time", []).append(time.time())
        dbLogger.debug("Start Query: %s", statement)

    @event.listens_for(Engine, "after_cursor_execute")
    def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        if not False:
            return
        total = time.time() - conn.info["query_start_time"].pop(-1)
        dbLogger.debug("Query Complete!")
        dbLogger.debug("Total Time: %f", total)

    # Tracks files upload set
    sounds = UploadSet("sounds", AUDIO)
    configure_uploads(app, sounds)

    # Album artwork upload set
    artworkalbums = UploadSet("artworkalbums", Reel2bitsDefaults.artwork_extensions_allowed)
    configure_uploads(app, artworkalbums)

    # Track artwork upload set
    artworksounds = UploadSet("artworksounds", Reel2bitsDefaults.artwork_extensions_allowed)
    configure_uploads(app, artworksounds)

    # User avatars
    avatars = UploadSet("avatars", Reel2bitsDefaults.avatar_extensions_allowed)
    configure_uploads(app, avatars)

    # Total max size upload for the whole app
    patch_request_class(app, app.config["UPLOAD_TRACK_MAX_SIZE"])

    app.flake_id = FlakeId()

    if register_blueprints:
        from controllers.main import bp_main

        app.register_blueprint(bp_main)

        from controllers.admin import bp_admin

        app.register_blueprint(bp_admin)

        # ActivityPub
        from controllers.api.v1.well_known import bp_wellknown

        app.register_blueprint(bp_wellknown)

        from controllers.api.v1.nodeinfo import bp_nodeinfo

        app.register_blueprint(bp_nodeinfo)

        from controllers.api.v1.ap import bp_ap

        # Feeds
        from controllers.feeds import bp_feeds

        app.register_blueprint(bp_feeds)

        # API
        app.register_blueprint(bp_ap)

        from controllers.api.v1.auth import bp_api_v1_auth

        app.register_blueprint(bp_api_v1_auth)

        from controllers.api.v1.accounts import bp_api_v1_accounts

        app.register_blueprint(bp_api_v1_accounts)

        from controllers.api.v1.timelines import bp_api_v1_timelines

        app.register_blueprint(bp_api_v1_timelines)

        from controllers.api.v1.notifications import bp_api_v1_notifications

        app.register_blueprint(bp_api_v1_notifications)

        from controllers.api.tracks import bp_api_tracks

        app.register_blueprint(bp_api_tracks)

        from controllers.api.albums import bp_api_albums

        app.register_blueprint(bp_api_albums)

        from controllers.api.account import bp_api_account

        app.register_blueprint(bp_api_account)

        from controllers.api.reel2bits import bp_api_reel2bits

        app.register_blueprint(bp_api_reel2bits)

        # Pleroma API
        from controllers.api.pleroma_admin import bp_api_pleroma_admin

        app.register_blueprint(bp_api_pleroma_admin)

        # OEmbed
        from controllers.api.oembed import bp_api_oembed

        app.register_blueprint(bp_api_oembed)

        # Iframe
        from controllers.api.embed import bp_api_embed

        app.register_blueprint(bp_api_embed)

        swagger = Swagger(app, template=template)  # noqa: F841 lgtm [py/unused-local-variable]

        # SPA catchalls for meta tags
        from controllers.spa import bp_spa

        app.register_blueprint(bp_spa)

    @app.route("/uploads/<string:thing>/<path:stuff>", methods=["GET"])
    @cross_origin(origins="*", methods=["GET", "HEAD", "OPTIONS"], expose_headers="content-length", send_wildcard=True)
    def get_uploads_stuff(thing, stuff):
        if app.testing or app.debug:
            directory = safe_join(app.config["UPLOADS_DEFAULT_DEST"], thing)
            app.logger.debug(f"serving {stuff} from {directory}")
            return send_from_directory(directory, stuff, as_attachment=True)
        else:
            app.logger.debug(f"X-Accel-Redirect serving {stuff}")
            resp = Response("")
            resp.headers["Content-Disposition"] = f"attachment; filename={stuff}"
            resp.headers["X-Accel-Redirect"] = f"/_protected/media/{thing}/{stuff}"
            resp.headers["Content-Type"] = ""  # empty it so Nginx will guess it correctly
            return resp

    def render_tags(tags):
        """
        Given a dict like {'tag': 'meta', 'hello': 'world'}
        return a html ready tag like
        <meta hello="world" />
        """
        for tag in tags:

            yield "<{tag} {attrs} />".format(
                tag=tag.pop("tag"),
                attrs=" ".join(['{}="{}"'.format(a, html.escape(str(v))) for a, v in sorted(tag.items()) if v]),
            )

    @app.errorhandler(404)
    def page_not_found(msg):
        excluded = ["/api", "/.well-known", "/feeds", "/oauth/authorize"]
        if any([request.path.startswith(m) for m in excluded]):
            return jsonify({"error": "page not found"}), 404

        html = get_spa_html(app.config["REEL2BITS_SPA_HTML"])
        head, tail = html.split("</head>", 1)

        request_tags = get_request_head_tags(request)

        default_tags = get_default_head_tags(request.path)
        unique_attributes = ["name", "property"]

        final_tags = request_tags
        skip = []

        for t in final_tags:
            for attr in unique_attributes:
                if attr in t:
                    skip.append(t[attr])
        for t in default_tags:
            existing = False
            for attr in unique_attributes:
                if t.get(attr) in skip:
                    existing = True
                    break
            if not existing:
                final_tags.append(t)

        head += "\n" + "\n".join(render_tags(final_tags)) + "\n</head>"
        return head + tail

    @app.errorhandler(403)
    def err_forbidden(msg):
        if request.path.startswith("/api/"):
            return jsonify({"error": "access forbidden"}), 403
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 403,
            "message": gettext("Access forbidden"),
            "e": msg,
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 403

    @app.errorhandler(410)
    def err_gone(msg):
        if request.path.startswith("/api/"):
            return jsonify({"error": "gone"}), 410
        pcfg = {"title": gettext("Whoops, something failed."), "error": 410, "message": gettext("Gone"), "e": msg}
        return render_template("error_page.jinja2", pcfg=pcfg), 410

    if not app.debug:

        @app.errorhandler(500)
        def err_failed(msg):
            if request.path.startswith("/api/"):
                return jsonify({"error": "server error"}), 500
            pcfg = {
                "title": gettext("Whoops, something failed."),
                "error": 500,
                "message": gettext("Something is broken"),
                "e": msg,
            }
            return render_template("error_page.jinja2", pcfg=pcfg), 500

    @app.after_request
    def set_x_powered_by(response):
        response.headers["X-Powered-By"] = "reel2bits"
        return response

    # Register CLI commands
    app.cli.add_command(commands.db_datas)
    app.cli.add_command(commands.users)
    app.cli.add_command(commands.roles)
    app.cli.add_command(commands.tracks)
    app.cli.add_command(commands.system)

    return app
Beispiel #46
0
import urllib.request

from bs4 import BeautifulSoup
from flask import Flask, render_template, request, abort, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from flask_sslify import SSLify
import requests

from models import db
from models import User, Submission, AcceptedSubmission, Ranking

application = Flask(__name__)
sslify = SSLify(application)
application.config.from_object(os.environ['APP_SETTINGS'])
application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(application)

toolbar = DebugToolbarExtension(application)

# define header for urllib request
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) ' \
             'Chrome/58.0.3029.110 Safari/537.36'
hds = {'User-Agent': user_agent}
hds_json = {'User-Agent': user_agent, 'Content-Type': 'Application/json'}

# constants
RESULTS = ["기다리는 중", "재채점을 기다리는 중", "채점 준비중", "채점중", "맞았습니다!!", "출력 형식이 잘못되었습니다",
           "틀렸습니다", "시간 초과", "메모리 초과", "출력 초과", "런타임 에러", "컴파일 에러"]


def is_boj_user(user_id):
Beispiel #47
0
def configure_app(configure_name='default'):
    db.init_app(app=app)

    from config import config
    app.config.from_object(config[configure_name])
    config[configure_name].init_app(app=app)
Beispiel #48
0
from flask_sqlalchemy import SQLAlchemy
from models import db, User     # 다른 파일에서 모델을 가져와야 사용 가능
import os

app = Flask(__name__)

# flask app에 보낼 sqlalchemy 관련 설정
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db_flask.sqlite3'  # db 파일의 이름 설정
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False   # True가 기본값인데,
# sqlalchemy DB 객체 수정 및 신호 방출 등을 추적하므로 과도한 메모리를 사용해 False


# sqlalchemy 초기화
# db = SQLAlchemy(app)   # 파일이 합쳐진 경우

db.init_app(app)   # 파일이 분리된 경우

migrate = Migrate(app, db)


@app.route('/')
# 뷰 함수(route 아래에 있는 함수)
def index():
    # url_for('index') =>>> '/'  view함수의 route를 return한다
    # return redirect(url_for('index'))
    users = User.query.all()   # <5> 입력한 정보를 모두 보여줌
    return render_template('index.html', users=users)    # index.html에서 정보를 받아와서 보여주기 위해 users를 넣음

@app.route('/users/create')   # orm 동작만 가능하게 하면 되므로 페이지는 필요 없다
def create():   # bootstrap을 적용해 바로 위에 글씨가 붙음
    username = request.args.get('username')   # <3>이 페이지에서 create 함수를 통해 username과 email로 정보가 들어감
Beispiel #49
0
 def create_app(self):
     app = Flask(__name__)
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
     app.config['TESTING'] = True
     db.init_app(app)
     return app
Beispiel #50
0
        # 데이터 베이스에 insert
        db.session.add(led)
        # 변경 내용을 저장
        db.session.commit()

    return render_template('index.html',
                           led_states=led_states,
                           led_time=led_time)


if __name__ == "__main__":  # 직접 해당 파일을 실행 시, app이 실행됨
    basedir = os.path.abspath(os.path.dirname(__file__))
    print(basedir)
    print(__name__)

    dbfile = os.path.join(basedir, "db.sqlite")

    # sqlite db 접속 주소
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
    # 각 리쿼스트의 끝에 db 변동 사항을 자동 commit함
    app.config['SQLALCHEMY_COMMIT_IN_TEARDOWN'] = True
    # 개체 수정을 추적????? -> sqlAlchemy의 이벤트 기능을 사용할지에 대한 flag( 버그가 많데요 이 기능에 )
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # db
    # 초기화
    db.init_app(app)  # models.py에서 db = SQLAlchemy()가 있어서 가능함
    db.app = app
    db.create_all()  # 테이블을 생성
    app.run(host='0.0.0.0', port=5000, debug=True)
Beispiel #51
0
def register_db(app):
    db.init_app(app)
    db.app = app
Beispiel #52
0
def create_app(config, enable_config_file=False):
    """
    创建应用
    :param config: 配置信息对象
    :param enable_config_file: 是否允许运行环境中的配置文件覆盖已加载的配置信息
    :return: 应用
    """
    app = create_flask_app(config, enable_config_file)

    # 创建Snowflake ID worker
    from utils.snowflake.id_worker import IdWorker
    app.id_worker = IdWorker(app.config['DATACENTER_ID'],
                             app.config['WORKER_ID'], app.config['SEQUENCE'])

    # 限流器
    from utils.limiter import limiter as lmt
    lmt.init_app(app)

    # 配置日志
    from utils.logging import create_logger
    create_logger(app)

    # 注册url转换器
    from utils.converters import register_converters
    register_converters(app)

    from redis.sentinel import Sentinel
    _sentinel = Sentinel(app.config['REDIS_SENTINELS'])
    app.redis_master = _sentinel.master_for(
        app.config['REDIS_SENTINEL_SERVICE_NAME'])
    app.redis_slave = _sentinel.slave_for(
        app.config['REDIS_SENTINEL_SERVICE_NAME'])

    from rediscluster import StrictRedisCluster
    app.redis_cluster = StrictRedisCluster(
        startup_nodes=app.config['REDIS_CLUSTER'])

    # rpc
    app.rpc_reco = grpc.insecure_channel(app.config['RPC'].RECOMMEND)

    # Elasticsearch
    app.es = Elasticsearch(
        app.config['ES'],
        # sniff before doing anything
        sniff_on_start=True,
        # refresh nodes after a node fails to respond
        sniff_on_connection_fail=True,
        # and also every 60 seconds
        sniffer_timeout=60)

    # socket.io
    # app.sio = socketio.KombuManager(app.config['RABBITMQ'], write_only=True)

    # MySQL数据库连接初始化
    from models import db

    db.init_app(app)

    # 添加请求钩子
    from utils.middlewares import jwt_authentication
    app.before_request(jwt_authentication)

    # 注册用户模块蓝图
    from .resources.user import user_bp
    app.register_blueprint(user_bp)

    # 注册新闻模块蓝图
    from .resources.news import news_bp
    app.register_blueprint(news_bp)

    # 注册通知模块
    from .resources.notice import notice_bp
    app.register_blueprint(notice_bp)

    # 搜索
    from .resources.search import search_bp
    app.register_blueprint(search_bp)

    # 定义apscheduler的调度器对象
    # 保存到flask的app对象,方便在视图中使用调度器添加新的定时任务
    executors = {
        'default': ThreadPoolExecutor(20),
    }
    app.scheduler = BackgroundScheduler(executors=executors)

    # 由scheduler管理的定时任务 两种:
    # 一种是一开始就明确确定的 ,比如 修正redis的统计数据
    # 在此处定义 add_job
    # app.scheduler.add_job()

    # 添加定时修正统计数据的定时任务
    from .schedulers.statistic import fix_statistics
    # 每天的凌晨3点执行
    # 通过args 可以在调度器执行定时任务方法的时候,传递给定时任务方法参数
    # app.scheduler.add_job(fix_statistics, 'cron', hour=3, args=[app])

    # 为了测试方便,需要立即执行
    app.scheduler.add_job(fix_statistics, 'date', args=[app])

    # 另一种 是在flask运行期间,由视图函数产生的,动态添加的新定时任务
    # 在视图函数中 调用 current_app.scheduler.add_job来添加

    app.scheduler.start()  # 非阻塞,不会阻塞住flask程序的执行,会在后台单独创建进程或线程进行计时

    return app
Beispiel #53
0
            user)  #Aqui con la clase session.add() Añadimos a el usuario
        db.session.commit(
        )  #Y aqui con session.commit() Hacemos la peticion o guardamos los cambios o datoas generados
        #Aqui hacemos los repectivo para crear y enviar nuestro correo electronico a el correo
        #hasta qui lo deje porque no me envia el correo y se queda la pagina cargando y no lo envia
        msg = Message("Gracias Por Tu Registro!",
                      sender=app.config["MAIL_USERNAME"],
                      recipients=[user.email])
        msg.html = render_template("email.html", user=user.username)
        mail.send(msg)

        success_message = "Usuario Registrado en la Base de Datos "
        flash(success_message)

    return render_template("create_user.html", title=title, form=create_form)


if __name__ == '__main__':
    csrf.init_app(
        app
    )  #Ahora con csrf.init_app() de esta manera iniciamos nuestra aplicacion
    db.init_app(
        app)  #Aqui para iniciar nuestra base de datos a nuestra aplicacion
    mail.init_app(
        app)  #Aqui tenenmos q iniciar nuestros configuaciones para mail

    with app.app_context():  #Aqui vemos si tenemos las tablas
        db.create_all(
        )  #Aqui con la clase create_all() creamos nuestras tablas

    app.run(port=8080)
Beispiel #54
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    setup_db(app)
    app.debug = True
    db.init_app(app)
    migrate = Migrate(app, db)
    CORS(app)
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type,Authorization,true')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,PATCH,POST,DELETE,OPTIONS')
        return response

    # Get categories
    @app.route('/categories', methods=['GET'])
    def categories():
        """
        Returns:
            the list of all categories
        """

        categories = Category.query.all()
        formatted_categories = {
            category.id: category.type
            for category in categories
        }

        return jsonify({
            'success': True,
            'total_categories': len(formatted_categories),
            'categories': formatted_categories,
        })

    def paginate_questions(request, selection):
        page = request.args.get('page', 1, type=int)
        start = (page - 1) * QUESTIONS_PER_PAGE
        end = start + QUESTIONS_PER_PAGE
        questions = Question.query.all()
        formatted_questions = [question.format() for question in questions]

        current_questions = formatted_questions[start:end]

        return current_questions

    # Get questions

    @app.route('/questions', methods=['GET'])
    def questions():
        """
        Returns:
            the list of all questions
        """

        selection = Question.query.all()
        current_questions = paginate_questions(request, selection)

        if len(current_questions) == 0:
            abort(404)

        return jsonify({
            'success': True,
            'questions': current_questions,
            'totalQuestions': len(selection),
            'categories':
            {category.id: category.type
             for category in Category.query.all()},
        })

    # Delete question
    @app.route('/questions/<int:question_id>', methods=['DELETE'])
    def delete_question(question_id):
        """
        Returns:
            the result of deleting a question
        Args:
            question id
        """

        try:
            ques = Question.query.get(question_id)
            db.session.delete(ques)
            db.session.commit()
            return jsonify({
                'success': True,
            })

        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify({
                'success': False,
            })
        finally:
            db.session.close()

    # Create question

    @app.route('/questions/create', methods=['POST'])
    def create_question():
        """
        Returns:
            the result of creating a question
        """

        try:
            question = request.json['question']
            answer = request.json['answer']
            difficulty = request.json['difficulty']
            category = request.json['category']

            nQuestion = Question(
                question=question,
                answer=answer,
                category=category,
                difficulty=difficulty,
            )

            db.session.add(nQuestion)

            db.session.commit()

            page = request.args.get('page', 1, type=int)
            start = (page - 1) * 10
            end = start + 10
            questions = Question.query.all()
            formatted_questions = [question.format() for question in questions]
            return jsonify({
                'success': True,
            })

        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify({
                'success': False,
            })
        finally:
            db.session.close()

    # Search for question

    @app.route('/questions', methods=['POST'])
    def search_questions():
        """
        Returns:
            the result of searching for a questions
        """

        term = request.json['searchTerm']

        print("term is ")
        page = request.args.get('page', 1, type=int)
        start = (page - 1) * 10
        end = start + 10
        questions = Question.query.filter(Question.question.ilike(f'%{term}%'))
        formatted_questions = [question.format() for question in questions]
        return jsonify({
            'success': True,
            'questions': formatted_questions[start:end],
            'totalQuestions': len(formatted_questions),
            'categories':
            {category.id: category.type
             for category in Category.query.all()}
        })

    # Questions based on category

    @app.route('/categories/<category_id>/questions', methods=['GET'])
    def Questions_of_cat(category_id):
        """

        Returns:
            Shows list of questions based ona a specific category

        Args:
            category id

        """

        page = request.args.get('page', 1, type=int)
        start = (page - 1) * 10
        end = start + 10
        questions = Question.query.filter(Question.category == category_id)
        formatted_questions = [question.format() for question in questions]
        return jsonify({
            'success': True,
            'questions': formatted_questions[start:end],
            'totalQuestions': len(formatted_questions),
            'categories':
            {category.id: category.type
             for category in Category.query.all()}
        })

    # Quizz game

    @app.route('/quizzes', methods=['POST'])
    def createquiz():
        """

        Returns:
            returns a new question in the quiz such that it\'s not repeated

        """

        quiz_category = request.json['quiz_category']

        allQuestions = Question.query.filter(
            Question.category == quiz_category['id']).all()

        possibleQuestions = [q.id for q in allQuestions]
        print('possible questions: ', possibleQuestions)
        previousQuestions = request.json['previous_questions']
        print('previous questions: ', previousQuestions)

        possibilities = len(possibleQuestions)
        previous = len(previousQuestions)

        if possibilities == previous:
            return jsonify({'question': None})

        for possibility in possibleQuestions:
            if not possibility in previousQuestions:
                print('found: ', possibility)
                break

        currentQuestion = Question.query.get(possibility)
        print('current: ', currentQuestion)

        return jsonify({
            'question': {
                'id': currentQuestion.id,
                'question': currentQuestion.question,
                'answer': currentQuestion.answer,
                'difficulty': currentQuestion.difficulty,
                'category': currentQuestion.category
            },
        })

    # Error handling

    @app.errorhandler(404)
    def not_found(error):
        """

        returns:
            handling for 404 (Not found) Error

        """

        return jsonify({
            "success": False,
            "error": 404,
            "message": "Not found"
        }), 404

    @app.errorhandler(422)
    def unprocessable(error):
        """

        returns:
            handling for 422 (unprocessable) Error

        """

        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    @app.errorhandler(400)
    def Bad_request(error):
        """

        returns:
            handling for 400 (Bad request) Error

        """

        return jsonify({
            "success": False,
            "error": 400,
            "message": "Bad request"
        }), 400

    @app.errorhandler(405)
    def method_not_allowed(error):
        """

        returns:
            handling for 405 (method not allowed) Error

        """

        return jsonify({
            "success": False,
            "error": 405,
            "message": "method not allowed"
        }), 405

    @app.errorhandler(500)
    def Server_error(error):
        """

        returns:
            handling for 500 (Server error) Error

        """

        return jsonify({
            "success": False,
            "error": 500,
            "message": "Server error"
        }), 500

    @app.errorhandler(403)
    def forbidden(error):
        """

        returns:
            handling for 403 (forbidden) Error

        """

        return jsonify({
            "success": False,
            "error": 403,
            "message": "forbidden"
        }), 403

    @app.errorhandler(409)
    def Duplicate_resource(error):
        """

        returns:
            handling for 409 (Duplicate resource) Error

        """

        return jsonify({
            "success": False,
            "error": 409,
            "message": "Duplicate resource"
        }), 409

    return app
Beispiel #55
0
from flask import Flask, render_template, request, redirect
from models import db, Food
import plotly
import plotly.graph_objs as go
import pandas as pd
import json
import requests
import numpy as np

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///foods.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)  # db = SQLAlchemy(app)

URL = "https://api.calorieninjas.com/v1/nutrition?query={0}"
KEY = "sv/1TzlQR4ZWt3kugOovFg==HhXQzFLVFb97l5Ha"


@app.before_first_request  # ก่อนจะ request ครั้งแรก ให้ create_table() ทำงานก่อน
def create_table():
    db.create_all()


@app.route('/')
def index():
    food = Food.query.all()
    protein = []
    all_food = []
    for i in food:
        protein.append(i.protein)
Beispiel #56
0
def create_app():
    app = Flask(__name__)
    app.secret_key = "development-key"
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
    db.init_app(app)
    return app
Beispiel #57
0
def create_app():

    app = Flask(__name__)

    app.config.from_pyfile('settings.py')

    db.init_app(app)

    url_index = 'http://localhost:8716/'

    bootstrap = Bootstrap(app)
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    admin = flask_admin.Admin(
        app,
        'Superuser',
        base_template='my_master.html',
        template_mode='bootstrap3',
    )

    admin.add_view(ContentView(Content, db.session))
    admin.add_view(dataCatinView(DataCatin, db.session))
    admin.add_view(MyModelView(Role, db.session))
    admin.add_view(MyModelView(User, db.session))

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    h=admin_helpers,
                    get_url=url_for)

    @app.route('/', methods=['GET', 'POST'])
    def index():
        return render_template('index_page.html')

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        form = RegisterFormView()
        try:
            if form.validate_on_submit():
                hashed_password = form.password.data
                new_user = User(name=form.name.data,
                                email=form.email.data,
                                password=hashed_password)
                db.session.add(new_user)
                db.session.commit()

                return redirect(url_for('login'))
        except:
            return "<h2> Data yang di inputkan harus unique, sepertinya salah satu data yang Anda Masukan sudah terdaftar, " \
                   "Mohon ulangi input data dengan teliti...!!!  <br> <a href=" + url_index + "signup>Ulangi Input Data</a></h2>"

        return render_template('register.html', form=form)

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        form = LoginFormView(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                session['email'] = request.form['email']
                takeEmail = session['email'] = request.form['email']
                try:
                    takeRoles = User.query.filter_by(email=takeEmail).first()
                    takeRoles = takeRoles.roles
                    # takeRoles = ''.join(takeRoles)
                    print('testing', takeRoles)
                    user = User.query.filter_by(email=form.email.data).first()

                    if verify_password(user.password, form.password.data):
                        user.authenticated = True
                        db.session.add(user)
                        db.session.commit()
                        login_user(user)
                        login_user(user, remember=form.remember.data)
                        if takeRoles == ['user']:
                            return redirect(url_for('operator'))
                        elif takeRoles == []:
                            return redirect(url_for('society'))
                        else:
                            pass
                    else:
                        return '<h1>Invalid username or password</h1>'
                except:
                    return 'Sepertinya user yang Anda masukan belum terdaftar, mohon diperiksa lagi'

        return render_template('login.html', form=form)

    @app.route('/logout')
    @login_required
    def logout():
        logout_user()
        return redirect(url_for('index'))

    @app.route('/society')
    @login_required
    def society():
        dataUser = User('', '', '')

        id_user = current_user.id

        try:
            result, nik_catin_laki_laki = db.session.query(User, DataCatin.NIK_catin_laki_laki).join(DataCatin).\
                filter(DataCatin.user_id == current_user.id).first()
            result, nama_catin_laki_laki = db.session.query(User, DataCatin.nama_catin_laki_laki).join(DataCatin).\
                filter(DataCatin.user_id == current_user.id).first()
            result, nik_catin_perempuan = db.session.query(User, DataCatin.NIK_catin_perempuan).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, nama_catin_perempuan = db.session.query(User, DataCatin.nama_catin_perempuan).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, tanggal_daftar = db.session.query(User, DataCatin.tanggal_daftar).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, jadwal_nikah = db.session.query(User, DataCatin.jadwal_nikah).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, jam = db.session.query(User, DataCatin.jam).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, tempat_pelaksaan_nikah = db.session.query(User, DataCatin.tempat_pelaksaan_nikah).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
            result, status_pendaftaran = db.session.query(User, DataCatin.status_pendaftaran).join(DataCatin). \
                filter(DataCatin.user_id == current_user.id).first()
        except:
            nik_catin_laki_laki = '-'
            nama_catin_laki_laki = '-'
            nik_catin_perempuan = '-'
            nama_catin_perempuan = '-'
            tanggal_daftar = '-'
            jadwal_nikah = '-'
            jam = '-'
            tempat_pelaksaan_nikah = '-'
            status_pendaftaran = '-'

        # return render_template('society_dashboard.html', WELCOME=current_user.name)
        return render_template('society_dashboard.html',
                               WELCOME=current_user.name,
                               NIK_LAKI_LAKI=nik_catin_laki_laki,
                               NAMA_CATIN_LAKI_LAKI=nama_catin_laki_laki,
                               NIK_CATIN_PEREMPUAN=nik_catin_perempuan,
                               NAMA_CATIN_PEREMPUAN=nama_catin_perempuan,
                               TANGGAL_DAFTAR=tanggal_daftar,
                               JAM=jam,
                               JADWAL_NIKAH=jadwal_nikah,
                               TEMPAT_PELAKSAAN_NIKAH=tempat_pelaksaan_nikah,
                               STATUS_PENDAFTARAN=status_pendaftaran)

    @app.route('/societyinputdata', methods=['GET', 'POST'])
    @login_required
    def societyInputData():
        form = SocietyInputDataView(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                tanggal_daftar = time.strftime("%Y-%m-%d %H:%M:%S")
                add_jam = request.form['jam']
                new_data = DataCatin(form.NIK_catin_laki_laki.data,
                                     form.nama_catin_laki_laki.data,
                                     form.NIK_catin_perempuan.data,
                                     form.nama_catin_perempuan.data,
                                     tanggal_daftar, form.jadwal_nikah.data,
                                     add_jam, form.tempat_pelaksaan_nikah.data,
                                     current_user.id)
                db.session.add(new_data)
                db.session.commit()
                return redirect(url_for('society'))

        return render_template('society_input_data.html', form=form)

    @app.route('/operator', methods=['GET', 'POST'])
    @login_required
    def operator():
        if 'email' in session:
            name = current_user.name
            all_user_data = DataCatin.query.all()

            if request.method == 'POST':
                all_data_CSV = []
                for i in all_user_data:
                    # nik_CL_to_CSV.append({'NIK Catin Laki-laki': i.NIK_catin_laki_laki})
                    all_data_CSV.append({
                        'NIK Catin Laki-laki':
                        i.NIK_catin_laki_laki,
                        'Nama Catin Laki-laki':
                        i.nama_catin_laki_laki,
                        'NIK Catin Perempuan':
                        i.NIK_catin_perempuan,
                        'Nama Catin Perempuan':
                        i.nama_catin_perempuan,
                        'Tanggal Daftar':
                        i.tanggal_daftar,
                        'Jadwal Nikah':
                        i.jadwal_nikah,
                        'Jam':
                        i.jam,
                        'Tempat Pelaksanaan Nikah':
                        i.tempat_pelaksaan_nikah,
                        'Status Pendaftaran':
                        i.status_pendaftaran
                    })

                return send_csv(
                    all_data_CSV,
                    "laporan pendaftaran.csv", [
                        'NIK Catin Laki-laki', 'Nama Catin Laki-laki',
                        'NIK Catin Perempuan', 'Nama Catin Perempuan',
                        'Tanggal Daftar', 'Jadwal Nikah', 'Jam',
                        'Tempat Pelaksanaan Nikah', 'Status Pendaftaran'
                    ],
                    cache_timeout=1,
                    delimiter=';')

            return render_template('operator_dashboard.html',
                                   WELCOME=name,
                                   catin=all_user_data,
                                   DOWNLOAD_CSV='')
        else:
            return redirect(url_for('index'))

    @app.route('/csv')
    def csv():
        all_user_data = DataCatin.query.all()
        # nik_CL_to_CSV = []
        all_data_CSV = []
        for i in all_user_data:
            # nik_CL_to_CSV.append({'NIK Catin Laki-laki': i.NIK_catin_laki_laki})
            all_data_CSV.append({
                'NIK Catin Laki-laki': i.NIK_catin_laki_laki,
                'Nama Catin Laki-laki': i.nama_catin_laki_laki,
                'NIK Catin Perempuan': i.NIK_catin_perempuan,
                'Nama Catin Perempuan': i.nama_catin_perempuan,
                'Tanggal Daftar': i.tanggal_daftar,
                'Jadwal Nikah': i.jadwal_nikah,
                'Jam': i.jam,
                'Tempat Pelaksanaan Nikah': i.tempat_pelaksaan_nikah,
                'Status Pendaftaran': i.status_pendaftaran
            })
        return send_csv(
            all_data_CSV,
            "testing.csv", [
                '<b>NIK Catin Laki-laki</b>', 'Nama Catin Laki-laki',
                'NIK Catin Perempuan', 'Nama Catin Perempuan',
                'Tanggal Daftar', 'Jadwal Nikah', 'Jam',
                'Tempat Pelaksanaan Nikah', 'Status Pendaftaran'
            ],
            cache_timeout=1,
            delimiter=';')

    @app.route('/operatorAddData', methods=['GET', 'POST'])
    @login_required
    def operatorAddData():
        dataUser = User('', '', '')
        form = OperatorAddDataView(request.form)
        operator_name = current_user.name
        if request.method == 'POST':
            if form.validate_on_submit():
                add_jam = request.form['jam']
                new_data = DataCatin(form.NIK_catin_laki_laki.data,
                                     form.nama_catin_laki_laki.data,
                                     form.NIK_catin_perempuan.data,
                                     form.nama_catin_perempuan.data,
                                     form.tanggal_daftar.data,
                                     form.jadwal_nikah.data, add_jam,
                                     form.tempat_pelaksaan_nikah.data,
                                     current_user.id, False,
                                     form.status_pendaftaran.data)
                db.session.add(new_data)
                # db.session.commit()
                try:
                    db.session.commit()
                except:
                    return 'Data yang dimasukan sudah ada, mohon diulangi!!!'
                return redirect(url_for('operator'))

        return render_template('operatorAddData.html',
                               form=form,
                               OPERATOR_NAME=operator_name)

    @app.route('/delete_data/<id>')
    def delete_data(id):
        data = db.session.query(
            DataCatin, User).join(User).filter(DataCatin.id == id).first()
        if data.DataCatin.is_public:
            return render_template('catin_detail.html', catin=data)
        else:
            # if current_user.is_authenticated and data.DataCatin.user_id == current_user.id:
            if current_user.is_authenticated:
                data = DataCatin.query.filter_by(id=id).first()
                db.session.delete(data)
                db.session.commit()
        return redirect(url_for('operator'))

    @app.route('/catin_edit/<id>', methods=['GET', 'POST'])
    def catin_edit(id):
        data = db.session.query(
            DataCatin, User).join(User).filter(DataCatin.id == id).first()
        form = EditCatin(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                # if current_user.is_authenticated and data.DataCatin.user_id == current_user.id:
                if current_user.is_authenticated:
                    data = DataCatin.query.filter_by(id=id).first()
                    new_nik_L = form.NIK_catin_laki_laki.data
                    new_name_L = form.nama_catin_laki_laki.data
                    new_nik_P = form.NIK_catin_perempuan.data
                    new_name_P = form.nama_catin_perempuan.data
                    new_tanggal_daftar = form.tanggal_daftar.data
                    new_jadwal = form.jadwal_nikah.data
                    new_jam = request.form['jam']
                    new_tempat_pelaksaan_nikah = form.tempat_pelaksaan_nikah.data
                    new_status_pendaftaran = form.status_pendaftaran.data
                    try:
                        data.NIK_catin_laki_laki = new_nik_L
                        data.nama_catin_laki_laki = new_name_L
                        data.NIK_catin_perempuan = new_nik_P
                        data.nama_catin_perempuan = new_name_P
                        data.jadwal_nikah = new_jadwal
                        data.tanggal_daftar = new_tanggal_daftar
                        data.jam = new_jam
                        data.tempat_pelaksaan_nikah = new_tempat_pelaksaan_nikah
                        data.status_pendaftaran = new_status_pendaftaran
                        db.session.commit()

                    except Exception as e:
                        return {'error': str(e)}
                return redirect(url_for('operator'))

        return render_template('edit_catin.html', form=form, catin=data)

    return app
Beispiel #58
0
def create_app_v1(sql_db_url, port, app_folder, profile_folder, app_types,
                  comparator_path, comparator_file):
    """
    It creates the Flask REST app service
    """

    # We create the Flask Apo
    app = flask.Flask(__name__)
    CORS(app)  # pragma: no cover
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = sql_db_url
    app.config['LIVESERVER_PORT'] = port
    app.config['UPLOAD_FOLDER'] = app_folder
    app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
    app.config['APP_FOLDER'] = app_folder
    app.config['APP_PROFILE_FOLDER'] = profile_folder
    app.config['APP_TYPES'] = app_types
    app.config['COMPARATOR_PATH'] = comparator_path
    app.config['COMPARATOR_FILE'] = comparator_file
    app.config.from_object(Config())
    db.init_app(app)
    db.app = app

    # Create the Flask-Restless API manager.
    manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)

    # Create the REST methods for an Application
    manager.create_api(Application,
                       methods=['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
                       preprocessors={
                           'POST': [post_and_patch_application_preprocessor],
                           'PATCH_SINGLE':
                           [post_and_patch_application_preprocessor]
                       },
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST API for the Executable Configuration
    manager.create_api(Executable,
                       methods=['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST API for the Executable Configuration
    manager.create_api(
        Execution,
        methods=['GET', 'PATCH'],
        preprocessors={'PATCH_SINGLE': [patch_execution_preprocessor]},
        url_prefix=url_prefix_v1,
        results_per_page=-1)

    # Create the REST API for Execution Configuration
    manager.create_api(
        ExecutionConfiguration,
        methods=['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
        preprocessors={'PATCH_SINGLE': [patch_execution_script_preprocessor]},
        url_prefix=url_prefix_v1,
        results_per_page=-1)

    # Create the REST APi for the deployment
    manager.create_api(
        Deployment,
        methods=['GET', 'POST'],
        preprocessors={'POST': [post_deployment_preprocessor]},
        postprocessors={'POST': [post_deployment_postprocessor]},
        url_prefix=url_prefix_v1,
        results_per_page=-1)

    # Create the REST methods for a Testbed
    manager.create_api(Testbed,
                       methods=['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
                       preprocessors={
                           'POST': [post_testbed_preprocessor],
                           'PATCH_SINGLE': [put_testbed_preprocessor],
                           'PUT_SINGLE': [put_testbed_preprocessor]
                       },
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create teh REST methods for a Node
    manager.create_api(Node,
                       methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                       preprocessors={'PATCH_SINGLE': [put_node_preprocessor]},
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST methods for the GPU
    manager.create_api(GPU,
                       methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST methods for the MCP
    manager.create_api(MCP,
                       methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST methods for the Memory
    manager.create_api(Memory,
                       methods=['GET', 'POST', 'PUT', 'DELETE'],
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the REST methods for the CPU
    manager.create_api(CPU,
                       methods=['GET', 'POST', 'PUT', 'DELETE'],
                       url_prefix=url_prefix_v1,
                       results_per_page=-1)

    # Create the scheduler of tasks
    scheduler = APScheduler()
    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()
    app.scheduler = scheduler
    return app
Beispiel #59
0
def create_app(config, enable_config_file=False):
    """
    创建应用
    :param config: 配置信息对象
    :param enable_config_file: 是否允许运行环境中的配置文件覆盖已加载的配置信息
    :return: 应用
    """
    app = create_flask_app(config, enable_config_file)

    # 创建Snowflake ID worker
    from utils.snowflake.id_worker import IdWorker
    app.id_worker = IdWorker(app.config['DATACENTER_ID'],
                             app.config['WORKER_ID'], app.config['SEQUENCE'])

    # 如果在视图中需要生成分布式ID
    # id = current_app.id_worker.get_id()

    # 限流器
    from utils.limiter import limiter as lmt
    lmt.init_app(app)

    # 配置日志
    from utils.logging import create_logger
    create_logger(app)

    # 注册url转换器
    from utils.converters import register_converters
    register_converters(app)

    from redis.sentinel import Sentinel
    _sentinel = Sentinel(app.config['REDIS_SENTINELS'])
    app.redis_master = _sentinel.master_for(
        app.config['REDIS_SENTINEL_SERVICE_NAME'])
    app.redis_slave = _sentinel.slave_for(
        app.config['REDIS_SENTINEL_SERVICE_NAME'])

    from rediscluster import StrictRedisCluster
    app.redis_cluster = StrictRedisCluster(
        startup_nodes=app.config['REDIS_CLUSTER'])

    # 视图
    # current_app.redis_master.set()
    # current_app.redis_cluster.get()

    # rpc
    app.rpc_reco = grpc.insecure_channel(app.config['RPC'].RECOMMEND)

    # Elasticsearch
    app.es = Elasticsearch(
        app.config['ES'],
        # sniff before doing anything
        sniff_on_start=True,
        # refresh nodes after a node fails to respond
        sniff_on_connection_fail=True,
        # and also every 60 seconds
        sniffer_timeout=60)

    # socket.io
    # app.sio = socketio.KombuManager(app.config['RABBITMQ'], write_only=True)

    # MySQL数据库连接初始化
    from models import db

    db.init_app(app)

    # db = SQLAlchmey(app)

    # db = SQLAlchemy()
    # db.init_app(app_

    # 创建定时任务工具对象
    # 将scheduler对象保存到flask app对象中的目的,是方便视图执行的时候随时产生新的定时任务需求,可以借助current_app.scheduler.add_job()来
    # 动态添加新的定时任务

    executors = {
        'default': ThreadPoolExecutor(10),
    }

    app.scheduler = BackgroundScheduler(executors=executors)

    # 此处可以添加定时任务,这些定时任务与视图程序的执行无关,是在程序启动一开始就确定好的
    from .schedule import statistic
    # 每天凌晨3点执行
    app.scheduler.add_job(statistic.fix_statistics, 'cron', hour=3, args=[app])

    # 为了测试方便,立即执行
    # app.scheduler.add_job(statistic.fix_statistics, 'date', args=[app])

    # app.scheduler.add_job()
    # app.scheduler.add_job()
    # app.scheduler.add_job()

    app.scheduler.start()

    # 添加请求钩子
    from utils.middlewares import jwt_authentication
    app.before_request(jwt_authentication)

    # 注册用户模块蓝图
    from .resources.user import user_bp
    app.register_blueprint(user_bp)

    # 注册新闻模块蓝图
    from .resources.news import news_bp
    app.register_blueprint(news_bp)

    # 注册通知模块
    from .resources.notice import notice_bp
    app.register_blueprint(notice_bp)

    # 搜索
    from .resources.search import search_bp
    app.register_blueprint(search_bp)

    return app
Beispiel #60
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('settings.py')

    db.init_app(app)

    admin = Admin(app,
                  name='Flask01',
                  template_mode='bootstrap3',
                  index_view=SecuredAdminIndexView())
    admin.add_view(PageModelView(Page, db.session))
    admin.add_view(MenuModelView(Menu, db.session))

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    @app.route('/')
    @app.route('/<url>')
    def index(url=None):
        print('here', url)
        if url is not None:
            # contoh /about
            page = Page.query.filter_by(url=url).first()
        else:
            # contoh /
            page = Page.query.filter_by(is_homepage=True).first()

        if page is None:
            # TODO cute 404
            return 'Page not found for {} or homepage not set'.format(url)

        contents = 'empty'
        if page is not None:
            contents = page.contents

        menu = Menu.query.order_by('order')

        return render_template('index.html',
                               TITLE='Flask-01',
                               CONTENT=contents,
                               menu=menu)

    @app.route('/rahasia')
    @login_required
    def rahasia():
        return '<h1>Luke dies!<h1>'

    @app.route('/testdb')
    def testdb():
        import psycopg2

        con = psycopg2.connect(
            'dbname=flask01 user=devuser password=devpassword host=postgres')
        cur = con.cursor()

        cur.execute('select * from page;')

        id, title = cur.fetchone()
        con.close()
        return 'Output table page: {} - {}'.format(id, title)

    return app