Ejemplo n.º 1
0
def station_events_download(station_id):
    start = int(request.args.get('start', 0))
    search = request.args.get('search[value]', '')
    date_start = request.args.get('date_start', None)
    date_end = request.args.get('date_end', None)
    event_type = request.args.get('event_type', None)
    length = int(request.args.get('length', -1))

    events, total_count = get_log_events(station_id=station_id, start=start, search=search, date_start=date_start,
                            date_end=date_end, event_type=event_type, length=length)

    column_names = ["date", "category", "action", "content"]
    excel.init_excel(current_app)

    events_list = []
    file_name = "log_{}".format(station_id)
    for v in [event_type, date_start, date_end]:
        if v:
            file_name += "_{}".format(v)
    file_name += ".xlsx"

    return excel.make_response_from_query_sets(events.all(), column_names, "xlsx", file_name=file_name)
Ejemplo n.º 2
0
engine = create_engine(
    "mysql+pymysql://root:[email protected]:3306/bond?charset=utf8")
Base = declarative_base()
Base.metadata.reflect(engine)


class TradeHistory(Base):
    __table__ = Base.metadata.tables['TradeHistory']


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


@bond.route('/bondsearch', methods=['GET', 'POST'])
def search_bond():
    bond_name = request.form['bondname']
    Session_class = sessionmaker(bind=engine)
    session = Session_class()
    res = session.query(TradeHistory).filter(
        or_(TradeHistory.bond_name.like("%" + bond_name + "%"),
            TradeHistory.bond_code.like("%" + bond_name + "%"))).all()
    session.close()
    return render_template("bondsearch.html", res=res)


if __name__ == '__main__':
    excel.init_excel(bond)
    bond.run(host='0.0.0.0', port='8080', debug=True)
Ejemplo n.º 3
0
app = Flask(__name__,
            template_folder="app/templates",
            static_folder='app/static')

Bootstrap(app)

app.wsgi_app = ReverseProxied(app.wsgi_app, script_name=config.URL_APPLICATION)

app.config.from_pyfile('config/config.py')
app.secret_key = config.SECRET_KEY

db.init_app(app)
app.config['DB'] = db

excel.init_excel(app)

with app.app_context():
    app.jinja_env.globals['url_application'] = app.config["URL_APPLICATION"]

    if config.ACTIVATE_APP:

        @app.route('/')
        def index():
            ''' Route par défaut de l'application '''
            if "current_user" in session.keys():
                if session["current_user"]:
                    if session["current_user"]['id_profil'] > 2:
                        return redirect(url_for('delivery.deliveries'))
                    else:
                        return redirect(url_for('user.users'))
Ejemplo n.º 4
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    babel.init_app(app)
    excel.init_excel(app)
    configure_uploads(app, documents)

    app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
        if app.config['ELASTICSEARCH_URL'] else None
    app.redis = Redis.from_url(app.config['REDIS_URL'])
    app.task_queue = rq.Queue('microblog-tasks', connection=app.redis)

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    from app.customer import bp as customer_bp
    app.register_blueprint(customer_bp)

    from app.project import bp as project_bp
    app.register_blueprint(project_bp)

    from app.order import bp as order_bp
    app.register_blueprint(order_bp)

    from app.patient import bp as patient_bp
    app.register_blueprint(patient_bp)

    from app.sample import bp as sample_bp
    app.register_blueprint(sample_bp)

    from app.basket import bp as basket_bp
    app.register_blueprint(basket_bp)

    from app.process import bp as process_bp
    app.register_blueprint(process_bp)

    from app.setup import bp as setup_bp
    app.register_blueprint(setup_bp)

    from app.role import bp as role_bp
    app.register_blueprint(role_bp)

    from app.user import bp as user_bp
    app.register_blueprint(user_bp)

    from app.location import bp as location_bp
    app.register_blueprint(location_bp)

    from app.room import bp as room_bp
    app.register_blueprint(room_bp)

    from app.equipment_type import bp as equipment_type_bp
    app.register_blueprint(equipment_type_bp)

    from app.equipment import bp as equipment_bp
    app.register_blueprint(equipment_bp)

    from app.rack import bp as rack_bp
    app.register_blueprint(rack_bp)

    from app.box_type import bp as box_type_bp
    app.register_blueprint(box_type_bp)

    from app.box import bp as box_bp
    app.register_blueprint(box_bp)

    from app.store import bp as store_bp
    app.register_blueprint(store_bp)

    from app.aliquot import bp as aliquot_bp
    app.register_blueprint(aliquot_bp)

    from app.technique import bp as technique_bp
    app.register_blueprint(technique_bp)

    from app.study import bp as study_bp
    app.register_blueprint(study_bp)

    from app.subject import bp as subject_bp
    app.register_blueprint(subject_bp)

    from app.program import bp as program_bp
    app.register_blueprint(program_bp)

    from app.support import bp as support_bp
    app.register_blueprint(support_bp)

    from app.sample_type import bp as sample_type_bp
    app.register_blueprint(sample_type_bp)

    from app.sample_nature import bp as sample_nature_bp
    app.register_blueprint(sample_nature_bp)

    from app.disease import bp as disease_bp
    app.register_blueprint(disease_bp)

    from app.label import bp as label_bp
    app.register_blueprint(label_bp)

    from app.print import bp as print_bp
    app.register_blueprint(print_bp)

    from app.expedition import bp as expedition_bp
    app.register_blueprint(expedition_bp)

    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api/v1.0')

    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'],
                        app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                toaddrs=app.config['ADMINS'],
                subject='BioBank Failure',
                credentials=auth,
                secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        if app.config['LOG_TO_STDOUT']:
            stream_handler = logging.StreamHandler()
            stream_handler.setLevel(logging.INFO)
            app.logger.addHandler(stream_handler)
        else:
            if not os.path.exists('logs'):
                os.mkdir('logs')
            file_handler = RotatingFileHandler('logs/microblog.log',
                                               maxBytes=10240,
                                               backupCount=10)
            file_handler.setFormatter(
                logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                                  '[in %(pathname)s:%(lineno)d]'))
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('BioBank startup')

    return app
Ejemplo n.º 5
0
def create_app(config_name):
    if os.getenv('FLASK_CONFIG') == "production":
        app = Flask(__name__)
        app.config.update(
            SECRET_KEY=os.getenv('SECRET_KEY'),
            SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI'))

    else:
        app = Flask(__name__, instance_relative_config=True)
        # app.config.from_object(app_config[config_name])
        app.config.from_pyfile('config.py')

    # Import all models
    from .models import Member, Department, Umusarurob, InyongeraMusaruro, Employee, Role, Notification

    # A class to help in access the employees view flask admin extension.
    class EmployeeView(ModelView):
        form_columns = [
            'email', 'username', 'first_name', 'last_name', 'department_id',
            'phone_number'
        ]

    class MyModelView(ModelView):
        def is_accessible(self):
            return current_user.is_authenticated

        def inaccessible_callback(self, name, **kwags):
            return redirect(url_for('auth.login'))

    class MyAdminIndexView(AdminIndexView):
        def is_accessible(self):
            return current_user.is_authenticated

        can_edit = True
        edit_modal = True
        create_modal = True
        can_export = True
        can_view_details = True
        details_modal = True

    # Class to retrieve and diplay different models with their information.
    # To users via the flask admin extension.
    class CustomView(BaseView):
        @expose('/')
        def index(self):
            return self.render('admin/custom_index.html')

    admin = Admin(app,
                  name='aicos_admin',
                  base_template='my_master.html',
                  template_mode='bootstrap3',
                  index_view=MyAdminIndexView())
    admin.add_view(MyModelView(Member, db.session))
    admin.add_view(MyModelView(Department, db.session))
    admin.add_view(MyModelView(Umusarurob, db.session))

    #toolbar = DebugToolbarExtension(app)

    # Initiating different instances that are to be used with the application.
    Bootstrap(app)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_view = "auth.login"
    migrate = Migrate(app, db)
    #manager.init_app(app)
    flask_excel.init_excel(app)
    api.init_app(app)
    #toolbar.init_app(app)

    from app import models
    #from .overall import overall as overall_blueprint
    #app.register_blueprint(admin_blueprint, url_prefix="overall")

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

    # Importing different Blueprints that are defined within the platform.
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    from .aicos_members import aicos_members as aicos_members_blueprint
    app.register_blueprint(aicos_members_blueprint,
                           url_prefix='/aicos_members')

    from .aicos_req import aicos_req as aicos_req_blueprint
    app.register_blueprint(aicos_req_blueprint,
                           url_prefix='/aicos_requirements')

    from .aicos_stock_managment import aicos_stock_managment as aicos_stock_managment_blueprint
    app.register_blueprint(aicos_stock_managment_blueprint,
                           url_prefix='/aicos_stock_managment')
    """
    from .product.views import product as product_blueprintmember_profile
    app.register_blueprint(product_blueprint, url_prefix='/try')
    """

    parser = reqparse.RequestParser()
    parser.add_argument('name', type=str)
    parser.add_argument('description', type=float)

    # The route to define home without any other blueprint.
    @app.route('/')
    @app.route('/home')
    def home():
        return "Welcome to the Catalog Home. Muhiza Frank"

    # Class to try building API using extension that
    # interact with the models directly.
    class MemberApi(Resource):
        def get(self, id=None, page=1):
            if not id:
                products = Member.query.paginate(page, 10).items
            else:
                products = [Member.query.get(id)]
            if not products:
                abort(404)
            res = {}
            for product in products:
                res[product.id] = {
                    'name': product.name,
                    'plate': product.plate,
                }
            return json.dumps(res)

        def post(self):
            args = parser.parse_args()
            name = args['name']
            plate = args['plate']
            product = Role(name, plate)
            db.session.add(product)
            db.session.commit()
            res = {}
            res[product.id] = {
                'name': product.name,
                'plate': product.plate,
            }
            return json.dumps(res)
            """
                api.add_resource(
                   MemberApi,
                   '/api/member',
                   '/api/member/<int:id>'
                   )
            """

    # Routes to handle different errors that occur
    # during the interection between user and the platform.

    # Handline forbidden error.
    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html', title='Forbidden'), 403

    # Handline page not found error.
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('errors/404.html', title='Page Not Found'), 404

    # Handline internal server error, error
    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html', title='Server Error'), 500

    return app
Ejemplo n.º 6
0
from flask import Flask, request, jsonify, redirect, url_for
import flask_excel
import flask_excel as excel
from flask_sqlalchemy import SQLAlchemy  # sql operations

from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
from flask_restless import APIManager
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_admin import BaseView, expose
#from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)
flask_excel.init_excel(app)

#Configuring the database path
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@123@localhost/aicos'
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'

# Configuring the recaptha variables for user login checkings.
app.config['RECAPTCHA_PUBLIC_KEY'] = '6LdYIDcUAAAAAEE3N3tNqcYu50MJSTlGA5lwu5Pl'
app.config[
    'RECAPTCHA_PRIVATE_KEY'] = '6LdYIDcUAAAAAD8ayN_2Mkhauh_-MdK12XxdTLEo'

db = SQLAlchemy(app)
api = Api(app)
#manager = APIManager(app, flask_sqlalchemy_db=db)

# Configure the image uploading via Flask-Uploads
Ejemplo n.º 7
0
    FollowStatusChoices.Sent_sample: 4,
    FollowStatusChoices.Bought: 7,
}

# 限流字典
flask_app.ip_map = dict()

# 注册蓝图
flask_app.register_blueprint(sms_app)
flask_app.register_blueprint(auth_app)
flask_app.register_blueprint(crm_app)

# 初始化各种
manager = Manager(flask_app)
db.init_app(flask_app)
excel.init_excel(flask_app)
migrate = Migrate(flask_app, db)
manager.add_command('db', MigrateCommand)
celery = Celery(flask_app.name, broker=flask_app.config['CELERY_BROKER_URL'])
celery.conf.update(flask_app.config)
mongo = PyMongo(flask_app, uri=flask_app.config['MONGODB_URI'])
mail = Mail(flask_app)
login_manager = LoginManager(flask_app)
login_manager.login_view = 'auth.login'
login_manager.session_protection = 'strong'
login_manager.login_message_category = 'auth'


@login_manager.user_loader
def user_loader(user_id):
    return Seller.query.get(user_id)
Ejemplo n.º 8
0
from flask_login import UserMixin, AnonymousUserMixin
from app.exceptions import ValidationError
from . import db, login_manager
from .utils import hmac_sha256
from . import mongo
import pymongo, requests
from bson import ObjectId
import os, time
from os.path import join, dirname, realpath
from werkzeug.utils import secure_filename
from sqlalchemy import func, desc, asc, extract
import flask_excel as excel

# engine = create_engine('mysql://root@localhost:3306/ams')
apps = Flask(__name__)
excel.init_excel(apps)


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


class Role(db.Model):
    __tablename__ = 'ams_roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    added_time = db.Column(db.DateTime(), default=datetime.now())
    status = db.Column(db.Boolean, default=True)