示例#1
0
 def setUpClass(self):
     self.app = create_app()
     self.app_ctx = self.app.app_context()
     self.app_ctx.push()
     user = User(username='******', password=generate_password_hash('nik'))
     db.session.add(user)
     user1 = User(username='******', password=generate_password_hash('dan'))
     db.session.add(user1)
     newcommunity = Community(title='com', type='public')
     user = User.query.filter_by(username='******').first()
     newcommunity.moderators_users.append(user)
     newcommunity.subscribe_user.append(user)
     db.session.add(newcommunity)
     post = Post(title='mypost1',
                 html_page='',
                 author=user.username,
                 community=1,
                 rating=2)
     db.session.add(post)
     post = Post(title='mypost2',
                 html_page='',
                 author=user.username,
                 community=1)
     db.session.add(post)
     addNotification('nik', 'xoxo')
     db.session.commit()
     self.client = self.app.test_client()
示例#2
0
 def setUp(self):
     """configure virtual test environment."""
     os.environ['APP_SETTING'] = 'Testing'
     self.app = create_app(config_name='testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.client = self.app.test_client()
示例#3
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app("testing")

        api.init_app(self.app)
        api.add_namespace(questions_namespace)
        api.add_namespace(users_namespace)

        self.client = self.app.test_client()
示例#4
0
 def setUpClass(self):
     # create app package
     pkg = ZipFile('test.zip', 'w')
     pkg.write('testapp/application.py', arcname='application.py')
     pkg.write('testapp/manifest.json', arcname='manifest.json')
     pkg.write('testapp/requirements.txt', arcname='requirements.txt')
     pkg.write('testapp/wsgi.py', arcname='wsgi.py')
     pkg.close()
     # run
     self.pkg = os.path.join(os.path.dirname('.'), 'test.zip')
     if not os.path.exists(self.pkg):
         raise RuntimeError('Error creating test package: {0}'.format(self.pkg))
     self.app = app.test_client()
     # monkey patch app to load custom test_settings
     utils.applications.app = create_app('test_settings')
     self.application = Application()
示例#5
0
 def setUpClass(self):
     self.app = create_app()
     self.app_ctx = self.app.app_context()
     self.app_ctx.push()
     user = User(username='******', password=generate_password_hash('nik'))
     db.session.add(user)
     newcommunity = Community(title='com', type='public')
     db.session.add(newcommunity)
     post = Post(title='mypost1',
                 html_page='',
                 author=user.username,
                 community=1,
                 rating=2)
     db.session.add(post)
     post = Post(title='mypost2',
                 html_page='',
                 author=user.username,
                 community=1)
     db.session.add(post)
     db.session.commit()
     self.client = self.app.test_client()
import os
from config import Config, setConfig, create_app
from waitress import serve

if __name__ == '__main__':
    is_prod = False
    config = Config()

    if os.environ.get('WORK_ENV') == 'PROD':
        config.debug = False
        is_prod = True
    else:
        config.debug = True

    setConfig(config)
    app = create_app(config)
    serve(app, port=8000, host="0.0.0.0")
示例#7
0
 def setUpClass(self):
     self.app = create_app()
     self.app_ctx = self.app.app_context()
     self.app_ctx.push()
     self.client = self.app.test_client()
示例#8
0
from config import db, create_app
from models import Country, City

db.create_all(app=create_app())
app = create_app()
app.app_context().push()

# Data to initialize database with
COUNTRIES = [
    {'country': 'ni'}
]

CITIES = [
    {'city': 'Leon', 'active': True, 'country_id': 1},
    {'city': 'Chinandega', 'active': True, 'country_id': 1},
    {'city': 'Matagalpa', 'active': True, 'country_id': 1},
    {'city': 'Managua', 'active': True, 'country_id': 1},
    {'city': 'Granada', 'active': True, 'country_id': 1},
]

# Create the database
db.create_all()

# Iterate over the PEOPLE structure and populate the database
for country in COUNTRIES:
    c = Country(country=country['country'])
    db.session.add(c)

db.session.commit()

for city in CITIES:
示例#9
0
from flask import Flask, render_template
import config

app = config.create_app()
from routes.others import others
app.register_blueprint(others, url_prefix='/ic')
from routes.admin import admin
app.register_blueprint(admin, url_prefix='/ic/admin')
from routes.authentication import authentication
app.register_blueprint(authentication, url_prefix='/ic')


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


if __name__ == '__main__':
    from models.models import db
    db.create_all()
    app.run(debug=True)
示例#10
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config, create_app

app = Flask(__name__)
app.config.from_object(Config())

db = SQLAlchemy(app)
create_app(app)

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')
示例#11
0
from flask import request, abort, jsonify, render_template
import requests

from config import create_app

app = create_app(__name__)


@app.cache.cached(timeout=60)
@app.route("/")
def index():
    # main page
    return render_template("index.html", akid=request.values.get("akid"))


@app.route("/prefill", methods=["GET"])
def prefill():
    # prefill user info from akid
    akid = request.values.get("akid")
    if not akid:
        return abort(400, "akid param required")

    try:
        (mailing_id, user_id, token_hash) = akid.split(".")
    except ValueError:
        return abort(400, "malformed akid")

    user_url = "%s/rest/v1/user/%s" % (app.config["AK_BASE"], user_id)
    try:
        r = requests.get(user_url, auth=app.config["AK_AUTH"], timeout=(3.05, 20))
    except requests.Timeout:
示例#12
0
文件: app.py 项目: Mihail12/intu_test
from flask import request

from schemas import CategoryTypeListSchema
from models import CategoryType, GenderEnum, Retailer, Category, db
from config import create_app

app = create_app()

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


@app.route('/get_categories_type_list/')
def get_categories_type_list():
    type_schema = CategoryTypeListSchema()
    category_types = CategoryType.query.all()
    return type_schema.jsonify(category_types, many=True)


@app.route('/get_category_type/<typeid>/')
def get_category_type(typeid):
    category_type = CategoryType.query.filter_by(id=typeid)
    if category_type.count():
        type_schema = CategoryTypeListSchema()
        return type_schema.jsonify(category_type.first())
    return f"CategoryType with this id: {typeid} haven't found"


# POST:
# {
示例#13
0
import settings
from app.api.v1 import api
from app.api.v1.question import ns as questions_namespace
from app.api.v1.user import ns as users_namespace
from config import create_app

config_name = settings.APP_ENVIRONMENT_SETTINGS  # config_name = "development"
app = create_app(config_name)

api.init_app(app)
api.add_namespace(questions_namespace)
api.add_namespace(users_namespace)

if __name__ == '__main__':
    app.run()
示例#14
0
import requests
from celery import Celery
from flask_cors import CORS
import os
from dotenv import load_dotenv

from config import create_app
from config.config import app_config
from config.redis_db import redis_db

app = create_app('development')

load_dotenv()
# Add Redis URL configurations
app.config["CELERY_BROKER_URL"] = os.getenv("REDIS_CONFIG")
app.config["CELERY_RESULT_BACKEND"] = os.getenv("REDIS_CONFIG")
app.config.from_object(app_config["development"])

# Add periodic tasks
celery_beat_schedule = {
    "time_scheduler": {
        "task": "run.paginate_requested_data",
        # Run every second
        "schedule": 300.0,
    }
}

# configure celery

celery = Celery(app.name)
celery.conf.update(
示例#15
0
from config import create_app

app = create_app(config_name='development')

from api.views.auth import shauri_blueprint
from api.views.products import shauri_blueprint

app.register_blueprint(shauri_blueprint, url_prefix = '/v2/api/')
 def setUp(self):
     app = create_app(Config())
     app.app_context().push()
     self.app = app.test_client()
def dev():
    app = create_app('dev')
    app.run()
示例#18
0
文件: manager.py 项目: john966/lt_web
from config import create_app
from flask import Flask, request, redirect, session
from datetime import timedelta
import os

flask_app = create_app()

flask_app.config['SECRET_KEY'] = os.urandom(24)  #每一次服务器启动后,SECRET_KEY(盐)不一样
flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  #配置过期时间


@flask_app.before_request
def is_login():  # 判断是否登录
    # 白名单设置,判断为登录页面时
    if request.path == "/login":
        # 跳过处理
        return None
    # 判断session是不存在时
    if not session.get("userinfo"):
        # 重定向到登录页面
        return redirect("/login")


if __name__ == '__main__':
    flask_app.run("0.0.0.0", 8000, debug=True)
示例#19
0
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
from flaskext.mongoalchemy import MongoAlchemy
from config import create_app
from uuid import uuid4
from datetime import datetime

app = create_app()
db = MongoAlchemy(app)

class Log(db.Document):
    config_collection_name = 'logs'

    uuid = db.ComputedField(db.StringField(), lambda x: str(uuid4()), one_time=True)
    date = db.ComputedField(db.DateTimeField(), lambda x: datetime.utcnow(), one_time=True)
    level = db.IntField()
    name = db.StringField()
    message = db.StringField()

    @classmethod
    def clear(obj):
        Log._session.remove_query(Log).execute()
示例#20
0
# -*- coding: utf-8 -*-
import collections
import csv
import sys
import os
import json
from flask import render_template, redirect, Markup, request
import markdown
import config
import oauth
import requests as rq

sys.path.append("kwoc")

app, sess = config.create_app()
sess.init_app(app)

# Load stats.json file
dir_path = os.path.dirname(os.path.realpath(__file__))
root_dir = '/'.join(dir_path.split('/')[:-1])

stats_json = root_dir + '/gh_scraper/stats/stats.json'
with open(stats_json, 'r') as f:
    stats_dict = json.load(f)

# Separate people with non-zero contributions
non_zero_contributions = {}
zero_contributions = {}
for user, userdata in stats_dict.items():
    contribs = 0
    contribs += userdata['no_of_commits']
示例#21
0
import os

from dotenv import load_dotenv

from config import create_api, create_app, scheduler
from utils.handle import handle_success

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
api = create_api(app)


@app.route('/')
def root_path():
    return handle_success()


@scheduler.task('interval', id='do_job_1', seconds=5, misfire_grace_time=900)
def job1():
    print('Job 1 executed')
示例#22
0
from config import create_app

server = create_app()

if __name__ == '__main__':
    server.run(debug=True, host='0.0.0.0')
示例#23
0
文件: app.py 项目: BuiHuyPhuc/prophet
import os
from flask_bootstrap import Bootstrap
from werkzeug.utils import secure_filename
from flask import request, render_template, flash, redirect, url_for
import prophet_util
import config
import validations as val

app = config.create_app(__name__)


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


@app.route('/', methods=['POST'])
def upload():
    if 'upload' not in request.files:
        flash('No file uploaded', 'danger')
        return redirect(url_for('index'))

    file = request.files['upload']
    if file and config.allowed_file(file.filename):
        filepath = get_filepath(file)
        file.save(filepath)
        app.config['UPLOADED_FILE'] = filepath
        validations = val.validate_csv(filepath)
        if not validations:
            prophet_util.create_plots(filepath)
            return redirect(url_for('show'))
示例#24
0
        msg = db.blpop(settings.TASK_QUEUE_NAME)
        print('Running task: {0}'.format(msg))
        func, task_id, args, kwargs = pickle.loads(msg[1])
        qkey = settings.TASK_QUEUE_NAME
        key = '{0}:{1}'.format(qkey, task_id)
        data = {'date': time.time(), 'task_id': task_id, 'status': 'running', 'result': None}
        db.set(key, json.dumps(data))
        try:
            rv = func(*args, **kwargs)
            data['status'] = 'complete'
        except Exception, e:
            import traceback
            traceback.print_exc()
            rv = e
            data['status'] = 'error'
        if not isinstance(rv, dict):
            rv = str(rv)
        data['result'] = rv
        if rv is not None:
            db.set(key, json.dumps(data))
            db.expire(key, rv_ttl)

if __name__=='__main__':
    print('Starting queue...')
    try:
        app = config.create_app()
        queue_daemon(app)
    except KeyboardInterrupt:
        print('Exiting...')

示例#25
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
示例#26
0
 def setUp(self):
     self.app = create_app('testing')
     self.server = fakeredis.FakeServer()
     self.fake_redis_db = fakeredis.FakeStrictRedis(server=self.server)
     self.client = app.test_client(self)
示例#27
0
#!/usr/bin/env python
# Copyright 2012 Arcus Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from flask.ext.cache import Cache
import config

cache = Cache(config.create_app())
示例#28
0
from utils.article import get_text, analyze_text
from utils.celery import make_celery
from models.article_model import ArticleModel
from config import create_app
from db import connect_db

celery = make_celery(create_app())


@celery.task
def parse_text_to_db(url):
    article = ArticleModel(url)
    text = get_text(url)
    tokens, entities, parse_tree = analyze_text(text)

    # upsert article item
    fields = {
        "url": url,
        "text": text,
        "tokens": tokens,
        "entities": entities,
        "tree": parse_tree
    }

    return article.upsert(fields)


@celery.task
def sync_articles():
    # compares ids from pocket-list with articles
    # and starts analysis tasks on missing items
示例#29
0
文件: api.py 项目: amstee/NeoRestAPI
from gevent import monkey
monkey.patch_all()

import sys
from config.loader import neo_config
from config import create_app, socketio, NeoAPI, sockets

if __name__ == '__main__':
    if neo_config.load_config():
        neo_config.set_project_variables()
        app = create_app(neo_config)
        socketio.run(app=app,
                     port=neo_config.port,
                     host=neo_config.host,
                     debug=neo_config.debug)
        sys.exit(0)
    else:
        print("An error occured loading the configuration file",
              file=sys.stderr)
        sys.exit(1)