Exemple #1
0
 async def get_application(self):
     app = web.Application()
     setup_routes(app)
     setup_middlewares(app)
     setup_db(app, self.dsn)
     self.app = app
     return app
Exemple #2
0
def setup():
    global memory_db
    if not memory_db == None:
        return
    memory_db = TestConnection()
    db.setup_connection_factory(memory_db.get_connection, memory_db.done_connection)
    db.setup_db('admin', 'password')
Exemple #3
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "users_test"
        self.database_path = f"postgresql://*****:*****@localhost:5432/{self.database_name}"
        setup_db(self.app, self.database_path)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

        self.new_user = {
            'name': 'NAME',
            'username': '******',
            'password': '******'
        }
        self.invalid_user = {
            'name': 'invalid',
            'username': '******',
            'password': '******'
        }

        self.search_term = {'search_term': 'USERNAME'}
        self.invalid_search_term = {'search_term': 'invalid'}
Exemple #4
0
def main():
    setup_logging()
    logging.info('Starting DB setup')
    setup_db()
    logging.info('Fetching EPC data')
    fetch_epc_data()
    logging.info('Writing EPC data to DB')
    write_data()
Exemple #5
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.register_blueprint(api_blueprint, url_prefix="/")

    # setup db.
    setup_db(config_class)

    # setup snowflake client connection.
    setup_snowflake_client(config_class)

    return app
Exemple #6
0
def make_app(loop=None):
    app = web.Application(loop=loop)

    app['static_root_url'] = '/static'
    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader(
                             os.path.join(os.path.dirname(__file__),
                                          'templates')))

    setup_routes(app)
    setup_db(app, loop)

    return app
Exemple #7
0
async def init_app(argv=None):
    app = web.Application()

    setup_routes(app)
    setup_jinja2(app, loader=FileSystemLoader(BASE_PATH / 'templates'))
    setup_swagger(app, swagger_url="/api/v1/doc", ui_version=2)
    setup_aiohttp_apispec(app=app,
                          title="Profiles documentation",
                          version="v1",
                          url="/api/docs/swagger.json",
                          swagger_path="/api/docs",
                          static_path="/api/static")
    setup_middlewares(app)
    setup_db(app, dsn=dsn)

    return app
Exemple #8
0
def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        help="increase verbosity",
                        action="count",
                        dest="verb",
                        default=0)
    parser.add_argument('-d',
                        help="SQLite database file",
                        action="store",
                        dest="db",
                        default=None)
    parser.add_argument('-l',
                        help="Log to file instead of stdout",
                        action="store",
                        dest="logfile",
                        default=None)

    parser.add_argument('-t',
                        help="Send digest emails every X minutes",
                        action="store",
                        dest="sendinterval",
                        default=1440,
                        type=int)

    args = parser.parse_args()

    global sendinterval
    sendinterval = args.sendinterval

    if args.db:
        db.setup_db(args.db)
    else:
        db.setup_db(":memory:")

    if args.logfile:
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            filename=args.logfile,
            level=logging.INFO)
    else:
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

    if args.verb:
        logger.setLevel((50 - args.verb * 10))
Exemple #9
0
    def build(self):
        if setup_db():
            print("Database created!")

        main_window = MainWindow()
        main_window.db = get_db_session()

        return main_window
Exemple #10
0
    def setUp(self):
        self.app = APP
        self.client = self.app.test_client
        self.database_path = DATABASE_PATH
        setup_db(self.app, self.database_path)

        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            self.db.create_all()

        self.movie = {
            'title': 'The Blacklist',
            'release_date': 'Sun, 24 May 2020 13:04:03 GMT'
        }

        self.actor = {'name': 'John Wick', 'age': 44, 'gender': 'Male'}
Exemple #11
0
def setup_app(app):
    """Do general app setup so we can run from gunicorn or command line"""
    global HOST, PORT
    setup_db()

    app.config['SESSION_TYPE'] = 'redis'
    app.config['SECRET_KEY'] = '12345abcde'
    app.config['REDIS_URL'] = get_redis_url()

    # a DictStore will store everything in memory
    STORE = DictStore()
    # this will replace the app's session handling
    KVSessionExtension(STORE, APP)

    PORT = int(os.environ.get('PORT', 5000))
    HOST = os.environ.get('HOST', 'localhost')
    LOGGER.info("Starting application on PORT=%d", PORT)
    # Bind to PORT if defined, otherwise default to 5000.
    app.debug = False
    #APP.testing = True
    app.secret_key = '12345abcde'
    RQDashboard(app)
Exemple #12
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "trivia_test"
        self.database_path = "postgres://*****:*****@#@{}/{}".format(
            'localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)

        self.new_question = {
            'question': 'What is Your Name ?',
            'difficulty': 5,
            'category': 1,
            'answer': 'Mario'
        }

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
Exemple #13
0
def load_server():
    ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_ctx.load_cert_chain(os.environ['CERT_FILE'], os.environ['KEY_FILE'])

    # since @gen.coroutine can't decorate __init__, must pass db_setup + cache
    mc = setup_db()

    http_server = httpserver.HTTPServer(\
        OarsApp(\
            mc,
        ),
        ssl_options=ssl_ctx,
    )
    http_server.listen(int(os.environ['TORNADO_PORT']))
Exemple #14
0
def app_factory(args=()):
    app = web.Application()

    app.on_startup.append(db.on_start(app))
    app.on_teardown.append(db.on_destruct(app))

    if '--create-table' in argv:
        app.on_startup.append(db.setup_db())

    app.router.add_get('/task/', task.get_tasks, name='get_tasks')
    app.router.add_post('/task/', task.create, name='create_task')
    app.router.add_get('/task/{id:\d+}', task.get_single, name='single_task')
    app.router.add_put('/task/{id:\d+}', task.update, name='update_task')
    app.router.add_delete('/task/{id:\d+}', task.remove, name='remove_task')

    return app
Exemple #15
0
         "beneficiary_core": row[17],\
         "beneficiary_jurisdiction": row[16],\
         "beneficiary_account": row[18],\
         "beneficiary_bank": row[19],\
         "beneficiary_bank_country": row[20],\

         "source_file": row[23],\
			#"id": 6049,

         "investigation": "%s:%s:%s"%(row[0],row[21],row[22]),\
         "purpose": row[6],\
         "date": row[1],\

         "amount_orig": row[2],\
         "amount_usd": row[5],\
         "amount_eur": row[4],\
         "amount_orig_currency": row[3]\
        })

    json2db(json_data)


if __name__ == '__main__':
    from db import setup_db
    setup_db()
    #data = api_util.get_json_cached(laundromat_json, laundromat_json_url)
    #json2db(data["data"])

    data = api_util.get_csv_cached(laundromat_csv, laundromat_csv_url)
    csv2db(data[1:])
Exemple #16
0
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from helper import download_image, get_hex, get_img
from db import setup_db, Images
import json

app = Flask(__name__)
db = setup_db(app)


@app.route('/', methods=['GET'])
def index():
    return 'Welcome to Flask API'


@app.route('/add_image', methods=['POST'])
def add_image():
    if request.data:
        data = json.loads(request.data.decode('utf-8'))
        if data['url'] and data['name'] and data['type']:
            image_loc = download_image(data['url'], data['name'], data['type'])
            image_hex = get_hex(image_loc)

            new_image = Images(image_url=data['url'],
                               image_hex=image_hex,
                               image_name=data['name'],
                               image_type=data['type'])

            Images.insert(new_image)
            return jsonify({'success': True, 'added': new_image.info()})
        abort(404)
Exemple #17
0
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import MetaData
from db import setup_db, connect_db
from models.collection import Collection
from models.document import Document
from models.collection_version import CollectionVersion
from models.keyword import Keyword
from models.signature import Signature

engine = connect_db()
setup_db(engine)
DBSession = sessionmaker(bind=engine)
meta = MetaData(bind=engine)


class Cache():
    """
    A Cache is an object used to communicate with the sqlalchemy database and store FreeJournal data locally

    Attributes:
        session: the sqlalchemy session for this Cache
    """
    def __init__(self):
        """
        Create a new database session to support
        insertion or removal of local data.
        """
        self.session = DBSession()

    def get_all_collections(self):
Exemple #18
0
urllib2.install_opener(opener)

if __name__ == "__main__":
    import json
    import socket

    options, args = parse_options()

    with open(options.config, 'r') as options_file:
        config = json.load(options_file)

    if options.daemonize:
        daemonize.create_daemon()

    metadata.bind = config["db_uri"]
    setup_db(options.init_db)

    pad_manager = PadManager(path(config["rss_directory"]), config["delay"])
    pad_manager.load()

    xmlrpc_interface = xmlrpc_api.run_xmlrpc_server(
        pad_manager,
        **config["xmlrpc"]
    )

    if not options.test:
        try:
            pad_manager.mainloop()
        finally:
            xmlrpc_interface.instance.stop()
Exemple #19
0
            return True
        return False

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('index'))


# App configuration
app = Flask(__name__)
app.config['SERVER_NAME'] = 'fcit18.link'
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
login_manager = LoginManager()
login_manager.init_app(app)
admin = Admin(app, name='FCIT18.link',
              template_mode='bootstrap3', index_view=AdminIndex())
setup_db(app, admin, myAdminView, myUsersView)
captchaPrivateKey = os.environ.get('captchaPrivateKey')


@login_manager.user_loader
def load_user(user_id):
    if user_id is None:
        return None
    return User.query.get(int(user_id))

@app.before_request
def update_last_seen():
    if current_user.is_authenticated:
        current_user.lastSeen = datetime.utcnow()
        current_user.update()
Exemple #20
0
from bottle import Bottle, run
from routing import setup_routing
from db import setup_db
from db_data import seed_db

app = Bottle()

app.route()

setup_db(app)
seed_db(app)
setup_routing(app)

run(app, host='localhost', port=8080, debug=True)
Exemple #21
0
from concurrent.futures import ThreadPoolExecutor, CancelledError

from db import setup_db
from utils import prepare_queries, continue_from_last
from models import Scraper
from settings import settings_setup

ALPHA = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'

settings = settings_setup()
if settings.DEBUG:
    logging.getLogger('asyncio').setLevel(logging.WARNING)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(levelname)-8s %(message)s')

db = setup_db(settings.DB)


async def run_clients_pool(queries: Iterator, clients: List[Scraper]):
    n = len(clients)
    tasks = []
    q = True
    while q:
        # take a few queries from queries iterator
        q = list(islice(queries, 0, n))
        print(f"Parse queries: {', '.join(q)}...")
        if not len(q):
            break
        # create task and send query from slice
        # you can think about it as a chunk
        # technically, we can create as many task as we want
Exemple #22
0
def create_app(test_config=None):
    app = Flask(__name__)
    setup_db(app)
    CORS(app)

    # CORS Headers
    @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

    # Created a user
    @app.route('/users/create', methods=['POST'])
    def create_user():

        if request.method is not 'POST':
            abort(405)

        body = request.get_json()

        name = body.get('name')
        username = body.get('username')
        password = body.get('password')

        hashed_password = hash_password.hash(password)

        users = User.query.all()

        for u in users:
            if u.username == username:
                abort(409)

        try:

            user = User(name, username, hashed_password)
            user.insert()

            registered_user = User.query.filter(User.username == username).first()

            token = registered_user.generate_token()

            return jsonify({
                'success': True,
                'id': registered_user.id,
                'token': token
            })

        except:
            abort(422)

    # Logs in a user
    @app.route('/users/login', methods=['POST'])
    def login_user():

        if request.method is not 'POST':
            abort(405)

        body = request.get_json()

        username = body.get('username')
        password = body.get('password')

        hashed_password = hash_password.hash(password)

        users = User.query.all()

        try:

            for u in users:
                if u.username == username and u.password == hashed_password:

                    token = u.generate_token()

                    return jsonify({
                        'success': True,
                        'id': u.id,
                        'token': token
                    })
                else:
                    abort(401)

        except:
            abort(422)

    # Deletes a user by passing 'id' as a parameter
    @app.route('/users/<int:user_id>', methods=['DELETE'])
    def delete_user(user_id):

        if request.method is not 'DELETE':
            abort(405)

        user = User.query.filter(User.id == user_id).one_or_none()

        if user is None:
            abort(404)

        try:
            user.delete()

            return jsonify({
                'success': True,
                'id': user.id
            })

        except:
            abort(422)

    # Updates a user info by passing 'id' as a parameter
    @app.route('/users/<int:user_id>', methods=['PATCH'])
    def update_user(user_id):

        if request.method is not 'PATCH':
            abort(405)

        body = request.get_json()

        user = User.query.filter(User.id == user_id).one_or_none()

        if user is None:
            abort(404)

        name = body.get('name')
        username = body.get('username')
        password = body.get('password')

        hashed_password = password

        try:

            user.name = name
            user.username = username
            user.password = hashed_password

            return jsonify({
                'success': True,
                'id': user.id,
            })

        except:
            abort(422)

    # Fetches a list of paged users based on the provided search term using a form
    @app.route('/users/search', methods=['POST'])
    def search_question():

        if request.method is not 'POST':
            abort(405)

        search_term = request.form['search_term']
        users = User.query.filter(User.username.ilike(f'%{search_term}%')).all()

        if not len(users):
            abort(404)

        paged_users = paginate_users(request, users)

        return jsonify({
            'success': True,
            'users': paged_users,
            'total_users': len(users),
        })

    # Error handlers

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

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

    @app.errorhandler(405)
    def method_not_allowed(error):
        return jsonify({
            "success": False,
            "error": 405,
            "message": "method_not_allowed"
        }), 405

    @app.errorhandler(401)
    def unauthorized(error):
        return jsonify({
            "success": False,
            "error": 401,
            "message": "unauthorized"
        }), 401

    @app.errorhandler(409)
    def conflict(error):
        return jsonify({
            "success": False,
            "error": 409,
            "message": "conflict"
        }), 409

    return app
Exemple #23
0
 def __init__(self, connection, settings):
     plugin.Plugin.__init__(self, connection)
     self.startdate = datetime.now()
     self.pluginname = ''
     db.setup_db(settings['admin_username'], settings['admin_password'])
     db.reset_all_logins()
Exemple #24
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    setup_db(app)
    cors = CORS(app, resources={r"*": {"origins": "*"}})
    app.register_blueprint(questions)
    app.register_blueprint(categories)
    app.register_blueprint(quizzes)

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

    @app.errorhandler(Exception)
    def rise_error(error):
        return jsonify({
            'success': False,
            'error': error.code,
            'message': error.description
        }), error.code

    return app

    '''
  @TODO:
  Create an endpoint to handle GET requests
  for all available categories.
  '''

    '''
  @TODO:
  Create an endpoint to handle GET requests for questions,
  including pagination (every 10 questions).
  This endpoint should return a list of questions,
  number of total questions, current category, categories.

  TEST: At this point, when you start the application
  you should see questions and categories generated,
  ten questions per page and pagination at the bottom of the screen for three pages.
  Clicking on the page numbers should update the questions.
  '''

    '''
  @TODO:
  Create an endpoint to DELETE question using a question ID.

  TEST: When you click the trash icon next to a question, the question will be removed.
  This removal will persist in the database and when you refresh the page.
  '''

    '''
  @TODO:
  Create an endpoint to POST a new question,
  which will require the question and answer text,
  category, and difficulty score.

  TEST: When you submit a question on the "Add" tab,
  the form will clear and the question will appear at the end of the last page
  of the questions list in the "List" tab.
  '''

    '''
  @TODO:
  Create a POST endpoint to get questions based on a search term.
  It should return any questions for whom the search term
  is a substring of the question.

  TEST: Search by any phrase. The questions list will update to include
  only question that include that string within their question.
  Try using the word "title" to start.
  '''

    '''
  @TODO:
  Create a GET endpoint to get questions based on category.

  TEST: In the "List" tab / main screen, clicking on one of the
  categories in the left column will cause only questions of that
  category to be shown.
  '''

    '''
Exemple #25
0
def create_app(config=ProductionConfig):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config)
    CORS(app)
    mail = Mail(app)

    setup_db(app)
    SECRET_KEY = app.config['SECRET_KEY']

    @app.route("/")
    def index():
        return render_template('index.html')

    @app.post("/api/upload")
    @requires_auth(SECRET_KEY)
    def upload():
        if 'file' not in request.files:
            abort(400, "No file founded")
        file = request.files['file']
        if file.filename == '':
            abort(400, 'No selected file')
        file_ext = file.filename.rsplit('.', 1)[1].lower()
        if file_ext not in app.config['ALLOWED_EXTENSIONS']:
            abort(422, 'You cannot upload %s files' % file_ext)
        if file_ext != validate_image(file.stream):
            abort(422, 'Fake data was uploaded')

        # generate unique filename
        filename = uuid4().hex + "." + file_ext

        # Create upload folder if it doesnot exist
        if not path.isdir(app.config['UPLOAD_FOLDER']):
            mkdir(app.config['UPLOAD_FOLDER'])

        file.save(path.join(app.config['UPLOAD_FOLDER'], filename))

        return jsonify({'success': True, 'path': filename})

    @app.get("/uploads/<filename>")
    def uploaded_file(filename):
        try:
            return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
        except Exception:
            abort(404, "File not found")

    @app.post("/api/register")
    def register():
        data = request.get_json() or {}
        required_fields = [
            'first_name', 'last_name', 'email', 'username', 'password'
        ]
        # abort if any required field doesnot exist in request body
        for field in required_fields:
            if field not in data:
                abort(400, '%s is required' % field)

        first_name = str(data['first_name']).lower().strip()
        last_name = str(data['last_name']).lower().strip()
        email = str(data['email']).lower().strip()
        username = str(data['username']).lower().strip()
        password = str(data['password']).lower()
        job = str(data['job']).lower().strip() if data.get('job') else None
        phone = data.get('phone')

        # validating data
        if re.match(app.config['EMAIL_PATTERN'], email) is None:
            abort(422, 'Email is not valid')
        if len(password) < 8:
            abort(422, 'Password have to be at least 8 characters in length')
        if phone and re.match(app.config['PHONE_PATTERN'], phone) is None:
            abort(422, 'Phone is not valid')
        if len(username) < 4:
            abort(422, 'Username have to be at least 4 characters in length')

        default_role = Role.query.filter_by(name="general").one_or_none().id

        new_user = User(first_name, last_name, email, username, password,
                        default_role, job, phone)

        try:
            new_user.insert()
        except IntegrityError:
            # Integrity error means a unique value already exist in a different record
            if User.query.filter_by(email=email).one_or_none():
                msg = 'Email is already in use'
            elif User.query.filter_by(username=username).one_or_none():
                msg = "Username is already in use"
            else:
                msg = "Phone is already in use"
            abort(422, msg)

        return jsonify({
            'success': True,
            'token': gen_token(SECRET_KEY, new_user),
            'data': new_user.format(),
        })

    @app.patch("/api/user")
    @requires_auth(SECRET_KEY)
    def patch_user():
        data = request.get_json() or {}
        username = _request_ctx_stack.top.curr_user['sub']
        user = User.query.filter_by(username=username).one_or_none()
        # updating user data
        if 'first_name' in data:
            user.first_name = str(data['first_name']).lower().strip()
        if 'last_name' in data:
            user.last_name = str(data['last_name']).lower().strip()
        if 'email' in data:
            email = str(data['email']).lower().strip()
            if re.match(app.config['EMAIL_PATTERN'], email) is None:
                abort(422, 'Email is not valid')
            user.email = email
        if 'username' in data:
            username = str(data['username']).lower().strip()
            if len(username) < 4:
                abort(422,
                      'Username have to be at least 4 characters in length')
            user.username = username
        if 'password' in data:
            password = str(data['password']).lower().strip()
            if len(password) < 8:
                abort(422,
                      'Password have to be at least 8 characters in length')
            # passwords have to be hashed first
            user.set_pw(password)
        if 'phone' in data:
            phone = data['phone']
            if phone and re.match(app.config['PHONE_PATTERN'], phone) is None:
                abort(422, 'Phone is not valid')
            user.phone = phone
        if 'job' in data:
            user.job = str(data['job']).lower().strip()
        if 'avatar' in data:
            if not path.isfile(
                    path.join(app.config['UPLOAD_FOLDER'], data['avatar'])):
                abort(422, "Avatar is not valid")
            user.avatar = data['avatar']

        try:
            user.update()
        except IntegrityError:
            # Integrity error means a unique value already exist in a different record
            if 'email' in data and User.query.filter_by(
                    email=data['email']).one_or_none():
                msg = 'Email is already in use'
            elif 'username' in data and User.query.filter_by(
                    username=data['username']).one_or_none():
                msg = "Username is already in use"
            else:
                msg = "Phone is already in use"
            abort(422, msg)
        except Exception:
            abort(422)

        return jsonify({
            'success': True,
            'data': user.format(),
        })

    @app.post('/api/login')
    def login():
        data = request.get_json() or {}
        if 'username' not in data or 'password' not in data:
            abort(400, 'username and password expected in request body')

        username = data['username']
        password = data['password']
        user = User.query.filter_by(username=username).one_or_none()
        if not user or not user.checkpw(str(password)):
            abort(422, 'username or password is not correct')

        return jsonify({
            'success': True,
            'token': gen_token(SECRET_KEY, user),
            'data': user.format(),
        })

    @app.get('/api/notifications')
    @requires_auth(SECRET_KEY)
    def get_user_notifications():
        username = _request_ctx_stack.top.curr_user['sub']
        user = User.query.filter_by(username=username).one_or_none()
        notifications, meta = paginate(user.notifications,
                                       request.args.get('page', 1, int))
        unread_count = Notification.query.filter_by(user_id=user.id,
                                                    read=False).count()

        return jsonify({
            'success':
            True,
            'data': [notification.format() for notification in notifications],
            'unread_count':
            unread_count,
            'meta':
            meta
        })

    @app.get('/api/questions')
    def get_questions():
        all_questions = Question.query.order_by(
            Question.created_at.desc()).all()
        questions, meta = paginate(all_questions,
                                   request.args.get('page', 1, int))
        return jsonify({
            'success': True,
            'data': [question.format() for question in questions],
            'meta': meta
        })

    @app.get('/api/questions/<int:question_id>')
    def show_question(question_id):
        question = Question.query.get(question_id)
        if question == None:
            abort(404)
        # add list of the question answers to the question dict
        answers = [answer.format() for answer in question.answers]
        question = question.format()
        question.update(answers=answers)
        return jsonify({'success': True, 'data': question})

    @app.post('/api/questions')
    @requires_auth(SECRET_KEY)
    def post_question():
        data = request.get_json() or []
        if 'content' not in data:
            abort(400, 'content expected in request body')

        # sanitize input
        content = bleach.clean(data['content'])
        # supporting markdown
        content = markdown(content)
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        new_question = Question(user_id, content)
        try:
            new_question.insert()
        except Exception:
            abort(422)

        return jsonify({'success': True, 'data': new_question.format()})

    @app.patch('/api/questions/<int:question_id>')
    @requires_auth(SECRET_KEY)
    def patch_question(question_id):
        data = request.get_json() or []
        question = Question.query.get(question_id)
        if question == None:
            abort(404, 'question not found')
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        # check if current user owns the target question
        if user_id != question.user_id:
            raise AuthError('You can\'t update others questions', 403)

        # update accepted answer
        if 'accepted_answer' in data:
            answer = Answer.query.get(data['accepted_answer'])
            if not answer or answer.question_id != question_id:
                abort(400, 'the provided answer is not valid')
            question.accepted_answer = data['accepted_answer']
        # update question content
        if 'content' in data:
            # sanitize input
            content = bleach.clean(data['content'])
            # supporting markdown
            question.content = markdown(content)

        try:
            question.update()
        except Exception:
            abort(422)

        return jsonify({'success': True, 'data': question.format()})

    @app.delete('/api/questions/<int:question_id>')
    @requires_auth(SECRET_KEY)
    def delete_question(question_id):
        question = Question.query.get(question_id)
        if question == None:
            abort(404)
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        # check if the current user owns the target question
        if user_id != question.user_id:
            if not requires_permission('delete:questions'):
                raise AuthError(
                    'You don\'t have '
                    'the authority to delete other users questions', 403)
        try:
            question.delete()
        except Exception:
            abort(422)
        return jsonify({'success': True, 'deleted_id': int(question_id)})

    @app.get('/api/answers/<int:answer_id>')
    def show_answer(answer_id):
        answer = Answer.query.get(answer_id)
        if answer == None:
            abort(404)
        return jsonify({'success': True, 'data': answer.format()})

    @app.post('/api/answers')
    @requires_auth(SECRET_KEY)
    def post_answer():
        data = request.get_json() or []
        if 'content' not in data:
            abort(400, 'content expected in request body')
        if 'question_id' not in data:
            abort(400, 'question_id expected in request body')
        question = Question.query.get(data['question_id'])
        if question == None:
            abort(404, 'question not found')
        # sanitize input
        content = bleach.clean(data['content'])
        # supporting markdown
        content = markdown(content)
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        new_answer = Answer(user_id, question.id, content)
        try:
            new_answer.insert()
        except Exception:
            abort(422)
        return jsonify({'success': True, 'data': new_answer.format()})

    @app.patch('/api/answers/<int:answer_id>')
    @requires_auth(SECRET_KEY)
    def patch_answer(answer_id):
        data = request.get_json() or []
        answer = Answer.query.get(answer_id)
        if not answer:
            abort("404", "answer not found!")
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        # check if current user owns the target answer
        if user_id != answer.user_id:
            raise AuthError('You can\'t update others answers', 403)

        # update content
        if 'content' in data:
            # sanitize input
            content = bleach.clean(data['content'])
            # supporting markdown
            answer.content = markdown(content)

        try:
            answer.update()
        except Exception:
            abort(422)

        return jsonify({'success': True, 'data': answer.format()})

    @app.delete('/api/answers/<int:answer_id>')
    @requires_auth(SECRET_KEY)
    def delete_answer(answer_id):
        answer = Answer.query.get(answer_id)
        if answer == None:
            abort(404)
        # retrive user_id using username (which is stored in the stack by requires_auth decorator)
        username = _request_ctx_stack.top.curr_user['sub']
        user_id = User.query.filter_by(username=username).with_entities(
            User.id).one().id
        # check if the current user owns the target answer
        if user_id != answer.user_id:
            if not requires_permission('delete:answers'):
                raise AuthError(
                    'You don\'t have '
                    'the authority to delete other users answers', 403)
        try:
            answer.delete()
        except Exception:
            abort(422)
        return jsonify({'success': True, 'deleted_id': int(answer_id)})

    @app.get('/api/users/<username>')
    def show_user(username):
        user = User.query.filter_by(username=username).one_or_none()
        if not user:
            abort(404, 'User not found')

        return jsonify({'success': True, 'data': user.format()})

    @app.get('/api/users/<username>/questions')
    def get_user_questions(username):
        user = User.query.filter_by(username=username).one_or_none()
        if not user:
            abort(404, 'User not found')

        questions, meta = paginate(user.questions,
                                   request.args.get('page', 1, int))

        return jsonify({
            'success': True,
            'data': [questions.format() for questions in questions],
            'meta': meta
        })

    @app.post('/api/report/question')
    @requires_auth(SECRET_KEY)
    def report_question():
        username = _request_ctx_stack.top.curr_user['sub']
        question_id = request.get_json().get('question_id')
        if question_id is None:
            abort(400, 'question_id expted in request body')
        question = Question.query.get(question_id)
        if question is None:
            abort(404, 'question not found!')

        msg = Message('Reporting question')
        # email admin (my self)
        msg.add_recipient(app.config.get('MAIL_DEFAULT_SENDER'))
        msg.body = 'user "%s" has reported question "%i"' % (username,
                                                             question_id)
        msg.html = 'user <code>"%s"</code> has reported question <code>"%i"</code>' % (
            username, question_id)
        try:
            mail.send(msg)
        except Exception as e:
            abort(422, e)
        return jsonify({'success': True})

    @app.post('/api/report/answer')
    @requires_auth(SECRET_KEY)
    def report_answer():
        username = _request_ctx_stack.top.curr_user['sub']
        answer_id = request.get_json().get('answer_id')
        if answer_id is None:
            abort(400, 'answer_id expted in request body')
        answer = Answer.query.get(answer_id)
        if answer is None:
            abort(404, 'answer not found!')

        msg = Message('Reporting answer')
        # email admin (my self)
        msg.add_recipient(app.config.get('MAIL_DEFAULT_SENDER'))
        msg.body = 'user "%s" has reported answer "%i"' % (username, answer_id)
        msg.html = 'user <code>"%s"</code> has reported answer <code>"%i"</code>' % (
            username, answer_id)
        mail.send(msg)
        return jsonify({'success': True})

    # handling errors
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'success': False,
            'message': error.description,
            'error': 404
        }), 404

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            'success': False,
            'message': error.description,
            'error': 400
        }), 400

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

    @app.errorhandler(405)
    def method_not_allowed(error):
        return jsonify({
            'success': False,
            'message': error.description,
            'error': 405
        }), 405

    @app.errorhandler(413)
    def too_large(error):
        return jsonify({
            'success': False,
            'message': error.description,
            'error': 413
        }), 413

    @app.errorhandler(AuthError)
    def handle_auth_error(error):
        return jsonify({
            'success': False,
            'message': error.message,
            'error': error.code
        }), error.code

    # COMMANDS
    @app.cli.command('db_seed')
    def db_seed():
        # permission
        delete_users = Permission('delete:users')
        delete_answers = Permission('delete:answers')
        delete_questions = Permission('delete:questions')
        delete_users.insert()
        delete_answers.insert()
        delete_questions.insert()
        # roles
        general = Role('general')
        superamdin = Role('superadmin')
        superamdin.permissions.append(delete_users)
        superamdin.permissions.append(delete_answers)
        superamdin.permissions.append(delete_questions)
        general.insert()
        superamdin.insert()

    return app
def configure():
    app.config.from_object(default_settings)
    app.config.from_envvar('JOB_CONFIG', silent=True)
    db_url = app.config.get('SQLALCHEMY_DATABASE_URI')
    if not db_url:
        raise Exception('No db_url in config')
    db.setup_db(app)
    scheduler.add_listener(job_listener,
                           events.EVENT_JOB_EXECUTED |
                           events.EVENT_JOB_MISSED |
                           events.EVENT_JOB_ERROR)

    # need this for the tests
    try:
        scheduler.remove_jobstore('default')
    except KeyError:
        pass
    scheduler.add_jobstore(sqlalchemy_store.SQLAlchemyJobStore(
        url=db_url), 'default')

    login_manager = flogin.LoginManager()
    login_manager.setup_app(app)

    login_manager.anonymous_user = Anonymous
    login_manager.login_view = "login"

    global _users
    global _names

    _users = {
        app.config['USERNAME']: User('Admin', 0)
    }

    _names = dict((int(v.get_id()), k) for k, v in _users.items())

    @login_manager.user_loader
    def load_user(userid):
        userid = int(userid)
        name = _names.get(userid)
        return _users.get(name)

    logger = logging.getLogger()

    if not app.debug:
        stderr_handler = logging.StreamHandler(
            sys.stderr)

        stderr_handler.setLevel(logging.INFO)

        file_handler = logging.handlers.RotatingFileHandler(
            app.config.get('LOG_FILE'),
            maxBytes=67108864, backupCount=5)
        file_handler.setLevel(logging.INFO)

        mail_handler = logging.handlers.SMTPHandler(
            '127.0.0.1',
            app.config.get('FROM_EMAIL'),
            app.config.get('ADMINS', []),
            'CKAN Service Error')
        mail_handler.setLevel(logging.ERROR)


        if 'LOG_FILE' in app.config:
            logger.addHandler(file_handler)
        if 'FROM_EMAIL' in app.config:
            logger.addHandler(mail_handler)
        if 'STDERR' in app.config:
            logger.addHandler(stderr_handler)
    elif not app.testing:
        logger.addHandler(app.logger.handlers[0])

    app.wsgi_app = ProxyFix(app.wsgi_app)
Exemple #27
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    CORS(app)
    setup_db(app)

    # CORS Headers
    @app.after_request
    def after_request(response):

        # Allow requests headers ( Content-Type, Authorization)
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type,Authorization,true')

        # Allow specific requests methods (GET, POST, PATCH, DELETE, OPTIONS)
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,PATCH,POST,DELETE,OPTIONS')
        return response

    # Simple health check
    @app.route('/')
    def index():
        return "Healthy"

    # Run ONLY first time you start the app
    # db_drop_and_create_all()

    # ==================== MOVIES ==================== #

    '''
    GET /movies
    - Fetches all the movies from the database
    - Request arguments: None
    - Returns: A list of movies contain key:value pairs of id, title and
    release_date
    Response:
        {
            "success": true,
            "movies":
            [
                {
                    "id": 1,
                    "title": "Movie",
                    "release_date": "Sun, 12 July 2020 5:58:32 GMT"
                },
                {
                    "id": 2,
                    "title": "New movie",
                    "release_date": "Sun, 12 July 2020 5:58:32 GMT"
                }
            ]
        }
    '''

    @app.route('/movies', methods=['GET'])
    @requires_auth('get:movies')
    def get_movies(payload):

        try:

            # Query all movies from the database
            movies = Movie.query.all()

            # Format all movies
            response = [movie.format() for movie in movies]

            return jsonify({
                'success': True,
                'movies': response
            }), 200

        except SQLAlchemyError:
            abort(422)

    '''
    POST /movies
    - Creates a movie from the request's body
    - Request arguments: None
    - Returns: the created movie contains key:value pairs of id, title and
    release_date
    Body:
        {
            "title": "The Blacklist",
            "release_date": "Sun, 12 July 2020 5:58:32 GMT"
        }
    Response:
        {
            "success": true,
            "movie":
                {
                    "id": 1,
                    "title": "The Blacklist",
                    "release_date": "Sun, 12 July 2020 5:58:32 GMT"
                }
        }
    '''

    @app.route('/movies', methods=['POST'])
    @requires_auth('create:movie')
    def create_movie(payload):

        # Fetch request body
        body = request.get_json()

        # If body not provided, abort 400
        if not body:
            abort(400)

        try:

            # Retrieves the data from the body
            title = body['title']
            release_date = body['release_date']

            # if data not provided, abort 400
            if not title or not release_date:
                abort(400)

            # Check if there's matching with name
            db_movie = Movie.query.filter(Movie.title == title).one_or_none()

            # If there's matching, abort 409
            if db_movie:
                abort(409)

            # Create the new Movie and insert it in the db
            movie = Movie(title, release_date)

            movie.insert()

            return jsonify({
                'success': True,
                'movie': movie.format()
            }), 201

        except (TypeError, KeyError):
            abort(400)

        except SQLAlchemyError:
            abort(422)

    '''
    PATCH /movies/<int:id>
    - Updates a movie using the information provided by request's body
    - Request arguments: Movie id
    - Returns: the updated movie contains key:value pairs of id, title and
     release_date
    Body:
        {
            "title": "The Blacklist 8",
            "release_date": "Sun, 12 July 2020 5:58:32 GMT"
        }
    Response:
        {
            "success": true,
            "movie":
                {
                    "id": 1,
                    "title": "The Blacklist 8",
                    "release_date": "Sun, 12 July 2020 5:58:32 GMT"
                }
        }
    '''

    @app.route('/movies/<int:movie_id>', methods=['PATCH'])
    @requires_auth('update:movie')
    def update_movie(movie_id, payload):

        # Fetch request body
        body = request.get_json()

        # If body not provided, abort 400
        if not body:
            abort(400)

        try:

            # Retrieves the data from the body
            title = body['title']
            release_date = body['release_date']

            # Retrieves the movie from the database
            movie = Movie.query.filter(Movie.id == movie_id).one_or_none()

            # If there's no such movie, abort 404
            if not movie:
                abort(404)

            # Update the model with the data provided
            if title:
                movie.title = title
            if release_date:
                movie.release_date = release_date

            movie.update()

            return jsonify({
                'success': True,
                'movie': movie.format()
            }), 200

        except (TypeError, KeyError):
            abort(400)

        except SQLAlchemyError:
            abort(422)

    '''
    DELETE /movies/<int:id>
    - Updates a movie using the information provided by request's body
    - Request arguments: Movie id
    - Returns: the deleted movie id
    Response:
        {
            "success": true,
            "deleted": 1
        }
    '''

    @app.route('/movies/<int:movie_id>', methods=['DELETE'])
    @requires_auth('delete:movie')
    def delete_movie(movie_id, payload):

        try:

            # Retrieves the movie from the database
            movie = Movie.query.filter(Movie.id == movie_id).one_or_none()

            # If there's no such movie, abort 404
            if not movie:
                abort(404)

            movie.delete()

            return jsonify({
                'success': True,
                'deleted': movie.id
            }), 200

        except SQLAlchemyError:
            abort(422)

    # ==================== ACTORS ==================== #

    '''
    GET /actors
    - Fetches all the actors from the database
    - Request arguments: None
    - Returns: A list of actors contain key:value pairs of id, name, age and
    gender

    Response:
        {
            "success": true,
            "actors":
            [
                {
                    "id": 1,
                    "name": "John",
                    "age": 35,
                    "gender": "Male"
                },
                {
                    "id": 2,
                    "name": "Ivy",
                    "age": 34,
                    "gender": "Women"
                }
            ]
        }
    '''

    @app.route('/actors', methods=['GET'])
    @requires_auth('get:actors')
    def get_actors(payload):

        try:
            # Query all actors from the database
            actors = Actor.query.all()

            # Format all actors
            response = [actor.format() for actor in actors]

            return jsonify({
                'success': True,
                'actors': response
            }), 200

        except SQLAlchemyError:
            abort(422)

    '''
    POST /actors

    - Creates an actor from the request's body
    - Request arguments: None
    - Returns: the created actor contains key:value pairs of id, name, age and
    gender

    Body:
         {
             "name": "John",
             "age": 20,
             "gender": "Women"
         }

    Response:
        {
            "success": true,
            "actor":
                {
                    "id": 1
                    "name": "John",
                    "age": 20,
                    "gender": "Women"
                }
        }
    '''

    @app.route('/actors', methods=['POST'])
    @requires_auth('create:actor')
    def create_actor(payload):

        # Fetch request body
        body = request.get_json()

        # If body not provided, abort 400
        if not body:
            abort(400)

        try:

            # Retrieves the data from the body
            name = body['name']
            age = body['age']
            gender = body['gender']

            # if data not provided, abort 400
            if not name or not age or not gender:
                abort(400)

            # Check if there's matching with name
            db_actor = Actor.query.filter(Actor.name == name).one_or_none()

            # If there's matching, abort 409
            if db_actor:
                abort(409)

            # Create the new Actor and insert it in the db
            actor = Actor(name, age, gender)

            actor.insert()

            return jsonify({
                'success': True,
                'actor': actor.format()
            }), 201

        except (TypeError, KeyError):
            abort(400)

        except SQLAlchemyError:
            abort(422)

    '''
    PATCH /actors/<int:id>

    - Updates a actor using the information provided by request's body
    - Request arguments: Actor id
    - Returns: the updated actor contains key:value pairs of id, name, age and
    gender

    Body:
        {
            "name": "John",
            "age": 20,
            "gender": "Women"
        }

    Response:
        {
            "success": true,
            "actor":
                {
                    "id": 1,
                    "name": "John",
                    "age": 20,
                    "gender": "Women"
                }
        }
    '''

    @app.route('/actors/<int:actor_id>', methods=['PATCH'])
    @requires_auth('update:actor')
    def update_actor(actor_id, payload):

        # Fetch request body
        body = request.get_json()

        # If body not provided, abort 400
        if not body:
            abort(400)

        try:

            # Retrieves the data from the body
            name = body['name']
            age = body['age']
            gender = body['gender']

            # Retrieves the movie from the database
            actor = Actor.query.filter(Actor.id == actor_id).one_or_none()

            # If there's no such movie, abort 404
            if not actor:
                abort(404)

            # Update the model with the data provided
            if name:
                actor.name = name
            if age:
                actor.age = age
            if gender:
                actor.gender = gender

            actor.update()

            return jsonify({
                'success': True,
                'movie': actor.format()
            }), 200

        except (TypeError, KeyError):
            abort(400)

        except SQLAlchemyError:
            abort(422)

    '''
    DELETE /actors/<int:id>

    - Updates a movie using the information provided by request's body
    - Request arguments: Actor id
    - Returns: the deleted actor id

    Response:
        {
            "success": true,
            "deleted": 1
        }
    '''

    @app.route('/actors/<int:actor_id>', methods=['DELETE'])
    @requires_auth('delete:actor')
    def delete_actor(actor_id, payload):

        try:

            # Retrieves the movie from the database
            actor = Actor.query.filter(Actor.id == actor_id).one_or_none()

            # If there's no such movie, abort 404
            if not actor:
                abort(404)

            actor.delete()

            return jsonify({
                'success': True,
                'deleted': actor.id
            }), 200

        except SQLAlchemyError:
            abort(422)

    # ==================== ERROR HANDLING ==================== #

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

    @app.errorhandler(404)
    def not_found(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(409)
    def conflict(error):
        return jsonify({
            "success": False,
            "error": 409,
            "message": "conflict"
        }), 409

    @app.errorhandler(AuthError)
    def auth_error(error):
        return jsonify({
            "success": False,
            "error": error.status_code,
            "message": error.error
        }), error.status_code

    return app
Exemple #28
0
import db
import datetime

Session = db.setup_db('sqlite:///test_fpl_db.db')
session = Session()
session.add(
    db.HourlyUsageDataDB(time=datetime.datetime.now(),
                         kwh=12.2,
                         approx_cost=1.2,
                         top_temp=99))

session.commit()
Exemple #29
0
from flask import Flask, request, jsonify, make_response
from mongokit import ValidationError, RequireFieldError

from db import setup as setup_db
import models


app = Flask(__name__)

# Load config
app.config.from_object('wifipos.default_settings')
app.config.from_envvar('WIFIPOS_SETTINGS')

# Connect to database
db = setup_db(app).connection


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/upload', methods=['POST', 'GET']) # TODO remove get
def upload():
    sample = db.Wifisample()

    # param presence checking
    for k in ['x', 'y', 'z', 'level', 'essid', 'bssid']:
        if k not in request.form:
            return jsonify({ 'error': "missing parameter '%s'" % k })
def setup_db():
    db.setup_db()
    db.fill_tables('dataset/dataset/with/', 1, 10)
    db.fill_tables('dataset/dataset/without/', -1, 10)

    print(db.count_sig_and_non_sig_lines())