Esempio n. 1
0
def register_extensions(app):
    """
    扩展实例化
    :param app:
    :return:
    """
    db.init_app(app)
    moment.init_app(app)
    migrate.init_app(app=app, db=db)
    cache.init_app(app)

    login_manager.init_app(app)
    # 登录过滤保护
    login_manager.exempt_views((user_bp, demo_bp, audio_bp, img_api_bp, ocr_api_bp))

    session.init_app(app)

    csrf.init_app(app)
    # csrf过滤保护
    csrf.exempt_views((demo_bp, audio_bp, img_api_bp, ocr_api_bp))

    # 定时任务 解决FLASK DEBUG模式定时任务执行两次
    if os.environ.get('FLASK_DEBUG', '0') == '0':
        scheduler.init_app(app)
        scheduler.start()
    elif os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        scheduler.init_app(app)
        scheduler.start()
Esempio n. 2
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    rq.init_app(app)
    app.rq = rq
    store.init_app(app)
    rest.init_app(app, flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    limiter.init_app(app)
    for handler in app.logger.handlers:
        limiter.logger.addHandler(handler)

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.debug = True
Esempio n. 3
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    store.init_app(app)
    rest.init_app(app,
                  flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
Esempio n. 4
0
def register_extensions(app):
    db.init_app(app)
    oauth.init_app(app)
    socketio.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    moment.init_app(app)
Esempio n. 5
0
def configure_extensions(app):
    """ Configure app extension. """
    # flask SQLAlchemy
    db.init_app(app)
    db.create_all(app=app)

    # CSRF Protection
    csrf.init_app(app)

    @csrf.error_handler
    def csrf_error(reason):
        raise CsrfTokenError()

    # mail.init_app(app)

    # flask OAuthlib
    oauth.init_app(app)

    # Login Manger
    login_manager.init_app(app)

    #  Interface for anonymous users
    class AnonymousUserMixin(_AnonymousUserMixin):
        username = '******'
        firstName = ''
        lastName = ''
        email = ''
        role = Role.GUEST
        is_admin = False

    login_manager.login_view = 'auth.post_login'
    login_manager.session_protection = "strong"
    login_manager.anonymous_user = AnonymousUserMixin
Esempio n. 6
0
def create_app():
    app = Flask(__name__)
    app.config.from_envvar('CALAPHIO_CONFIG')

    # Register Blueprints
    app.register_blueprint(core)

    # Register Jinja Filters
    app.jinja_env.filters['sanitize_html'] = sanitize_html

    # Extensions
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    bootstrap.init_app(app)
    nav.init_app(app)
    principal.init_app(app)
    register_renderer(app, "renderer", BetterBootstrapRenderer)

    # Method Rewriter
    app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

    # Identity Loader
    identity_loaded.connect(on_identity_loaded, app, False)

    return app
Esempio n. 7
0
def register_extensions(app):
    db.init_app(app)
    moment.init_app(app)
    csrf.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)
    avatars.init_app(app)
def extensions(our_app):

    mail.init_app(our_app)
    csrf.init_app(our_app)
    login_manager.init_app(our_app)
    login_manager.login_view = 'user.login'
    login_manager.login_message_category = 'info'
    return None
Esempio n. 9
0
def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    ckeditor.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
Esempio n. 10
0
def extension(app):
    csrf.init_app(app)
    moment.init_app(app)
    migrate.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)
    db.init_app(app)
    return None
Esempio n. 11
0
def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    dropzone.init_app(app)
    moment.init_app(app)
    whooshee.init_app(app)
    avatars.init_app(app)
    csrf.init_app(app)
Esempio n. 12
0
def create_app(config_file):
    app = Flask(__name__)
    app.config.from_pyfile(config_file)

    db.init_app(app)
    csrf.init_app(app)

    app.register_blueprint(admin)
    app.register_blueprint(user)

    return app
Esempio n. 13
0
def configure_extensions(app):
    db.init_app(app)

    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.login'

    @login_manager
    def load_user(id):
        pass  # TODO: make it works
        #return user.query.get(id)

    login_manager.setup_app(app)
    csrf.init_app(app)
Esempio n. 14
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    rq.init_app(app)
    app.rq = rq
    store.init_app(app)
    rest.init_app(app,
                  flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    limiter.init_app(app)
    for handler in app.logger.handlers:
        limiter.logger.addHandler(handler)

    # stable list of admin phone numbers, cached in memory to avoid db hit for each call
    # disable in testing
    if app.config.get('TESTING', False):
        app.ADMIN_PHONES_LIST = []
    else:
        try:
            app.ADMIN_PHONES_LIST = filter(bool, [
                str(u.phone.national_number) if u.phone else None
                for u in User.query.all()
            ])
        except sqlalchemy.exc.SQLAlchemyError:
            # this may throw an error when creating the database from scratch
            pass

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.debug = True
Esempio n. 15
0
def extensions(app):
    """
    Register 0 or more extensions (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    debug_toolbar.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    return None
Esempio n. 16
0
def register_extensions_production(app):
    """Register Flask extensions."""

    from extensions import api
    api.init_app(app)
    cors.init_app(app, supports_credentials=True)
    # need this for true prod
    cors.init_app(
        app, 
        resources={
            r"/*": {"origins": "https://www.icarusmed.com"}
        }, 
        supports_credentials=True)

    jwt.init_app(app)
    csrf.init_app(app)

    return None
Esempio n. 17
0
def create_app():
    from extensions import csrf
    from extensions import login_manager
    from extensions import db
    from views.main import main
    from views.auth import auth

    app = Flask(__name__)
    env = os.environ.get('zen_env', 'dev')
    app.config.from_object(
        'config.Prod') if env == 'prod' else app.config.from_object(
            'config.Dev')
    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    app.register_blueprint(main, url_prefix=None)
    app.register_blueprint(auth, url_prefix='/auth')
    login_manager.login_view = 'auth.login'
    return app
Esempio n. 18
0
def configure_extensions(app):
    """ Configure app extension. """
    # flask SQLAlchemy
    db.init_app(app)
    db.create_all(app=app)

    # CSRF Protection
    csrf.init_app(app)

    @csrf.error_handler
    @xhr_or_template('errors/forbidden-page.html')
    def csrf_error(message):
        flash(message, 'danger')
        return {'status': 403}


    # mail.init_app(app)

    # Login Manger
    login_manager.init_app(app)
    login_manager.login_view = 'frontend.login'

    # Setup login manager anonymous class.
    class DefaultAnonymousUserMixin(AnonymousUserMixin):
        id = None
        firstName = None
        lastName = None
        username = '******'
        email = None
        dateJoined = None
        avatar = 'avatar.jpg' # TODO: find a better avatar img for guest users

        @staticmethod
        def is_admin():
            return False

    login_manager.anonymous_user = DefaultAnonymousUserMixin
Esempio n. 19
0
#from FlaskForm import Form
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField, DecimalField, FloatField
from flask import request, flash
from forms import MainControlForm, ThrottleControlForm, ChannelControlForm, ServerControlForm
from forms import CallsignForm
from forms import ChannelControlForm, ChannelForm, ChannelListForm

from wtforms import validators, ValidationError

from flask_wtf import CSRFProtect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'here-is-your-secret-key-ghost-rider'
app.secret_key = 'development key'
app.config.from_object(Config)
csrf.init_app(app)

global theStatus, theDataStatus, thePropStatus, statusmain
global statusFT8, statusWSPR, statusRG, statusSnap, statusFHR
# statusControl = 0
received = ""
dataCollStatus = 0;
theStatus = "Not yet started"
theDataStatus = ""
thePropStatus = 0
statusFT8 = 0
statusWSPR = 0
statusRG = 0
statusSnap = 0
statusFHR = 0
statusmain = 0
Esempio n. 20
0
def create_app():

    import os
    from os import environ
    import psycopg2
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate
    from flask_heroku import Heroku
    from flask_admin.contrib.sqla import ModelView
    from flask_wtf.csrf import CSRFProtect
    from flask import render_template, request, redirect, jsonify, url_for, flash, session
    from sqlalchemy.orm import relationship, sessionmaker
    from models import User, Order, Customer, Role, OrderDetails, Product, Supplier, Payment, Shipper, users_schema, orders_schema, products_schema, customers_schema, order_details_schema, suppliers_schema, payments_schema, shippers_schema, MyAdminIndexView, UserAdmin, RoleAdmin
    from flask_admin import Admin
    from flask_login import UserMixin, LoginManager, current_user, login_user, logout_user
    from flask_security import SQLAlchemyUserDatastore, Security, utils, login_required
    from wtforms.fields import PasswordField
    from passlib.hash import pbkdf2_sha256
    from flask_marshmallow import Marshmallow
    import stripe
    import datetime
    from flask_mail import Mail, Message
    from decimal import Decimal
    from flask_caching import Cache
    from flask_assets import Environment, Bundle
    from PIL import Image

    APPLICATION_NAME = "Kokeshi"

    app = Flask(__name__)
    csrf.init_app(app)
    app.config.from_pyfile('config_default.cfg')
    assets = Environment(app)

    try:
        app.config.from_envvar('KOKESHI_SETTINGS')
    except:
        pass

    # Flask Security Config
    app.config['SECURITY_REGISTERABLE'] = True

    # Flask-Mail Config
    app.config.update(dict(
        MAIL_SERVER=os.environ['MAIL_SERVER'],
        MAIL_PORT=465,
        MAIL_USERNAME=os.environ['MAIL_USERNAME'],
        MAIL_USE_TLS=False,
        MAIL_USE_SSL=True,
        MAIL_PASSWORD=os.environ['MAIL_PASSWORD'],
        SECURITY_PASSWORD_HASH='pbkdf2_sha512',
        SECURITY_PASSWORD_SALT=os.environ['SECURITY_PASSWORD_SALT']
    ))

    cache = Cache(app, config={'CACHE_TYPE': 'simple'})

    # Flask-Assets config
    scss_bundle = Bundle('scss/*.scss',
                         filters='pyscss, cssmin',
                         output='css/styles.css',
                         extra={'rel': 'stylesheet/scss'},
                         )
    js_bundle = Bundle('js/*.js',
                       filters='jsmin',
                       output='js/main.min.js',
                       )
    assets.register('scss_all', scss_bundle)
    assets.register('js_all', js_bundle)
    scss_bundle.build()
    js_bundle.build()

    imagePath = "static/img/artisan-placeholder.jpg"
    outputPath = "static/img/artisan-placeholder.webp"
    quality = "80"

    im = Image.open(imagePath)
    im.save(outputPath, 'webp', quality=quality)

    app.url_map.strict_slashes = False

    # Initialize the SQLAlchemy data store and Flask-Security.
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    # Create admin views.
    admin = Admin(app, index_view=MyAdminIndexView())
    admin.add_view(UserAdmin(User, db.session))
    admin.add_view(RoleAdmin(Role, db.session))

    # Stripe payments implementation.
    STRIPE_PUBLISHABLE_KEY = 'pk_test_GM1d2F2DgrIl6jnkIwSaZ8Dd'
    stripe_keys = {
        'secret_key': os.environ['STRIPE_SECRET_KEY'],
        'publishable_key': STRIPE_PUBLISHABLE_KEY
    }

    stripe.api_key = stripe_keys['secret_key']

    #################
    # App functions #
    #################

    #######################
    # User administration #
    #######################

    # Populate the db with products and placeholder data
    """@app.before_first_request
    def before_first_request():
        db.create_all()
        user_datastore.find_or_create_role(
            name='super', description='Super User')
        user_datastore.find_or_create_role(
            name='admin', description='Administrator')
        user_datastore.find_or_create_role(
            name='artisan', description='Artisan')

        encrypted_password = utils.encrypt_password('password')

        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(
                email='*****@*****.**',
                password=encrypted_password
            )
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(
                email='*****@*****.**',
                password=encrypted_password
            )
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(
                email='*****@*****.**',
                password=encrypted_password
            )

        db.session.commit()

        user_datastore.add_role_to_user('*****@*****.**', 'super')
        user_datastore.add_role_to_user('*****@*****.**', 'admin')
        user_datastore.add_role_to_user('*****@*****.**', 'artisan')
        db.session.commit()

        db_items = [
            Product(
                name="Zao Kokeshi",
                description="A traditional handcrafted Japanese Kokeshi doll, made with care to the height of the newborn child",
                price=200,
                is_available=True
            ),
            Product(
                name="Yonezawa Kokeshi",
                description="A traditional handcrafted Japanese Kokeshi doll, made with care to the height of the newborn child",
                price=200,
                is_available=True
            ),
            Product(
                name="Sagae Kokeshi",
                description="A traditional handcrafted Japanese Kokeshi doll, made with care to the height of the newborn child",
                price=200,
                is_available=True
            ),
            Product(
                name="Tendo Kokeshi",
                description="A traditional handcrafted Japanese Kokeshi doll, made with care to the height of the newborn child",
                price=200,
                is_available=True
            ),
            Product(
                name="Message",
                description="A handwritten message on the back of the kokeshi doll",
                price=50,
                is_available=True
            ),
            Supplier(
                name="Sato",
                phone="08011112222",
                email="*****@*****.**"
            ),
            Supplier(
                name="Suzuki",
                phone="08011199002",
                email="*****@*****.**"
            ),
            Supplier(
                name="Miyagi",
                phone="090000009999",
                email="*****@*****.**"
            ),
            Shipper(
                companyName="Kuro Neko",
                phone="08051516161",
                email="*****@*****.**",
                contactName="Kurosawa"
            )
        ]

        for item in db_items:
            db.session.add(item)

        db.session.commit()"""

    @app.route('/login', methods=['GET', 'POST'])
    def showLogin():
        """
        Use a custom LoginForm to validate with WTForms
        """
        form = LoginForm()
        if form.validate_on_submit():
            # Login and validate the user.
            # user should be an instance of the `User` class
            login_user(user)

            flask.flash('Logged in successfully.')

            next = flask.request.args.get('next')
            # is_safe_url should check if the url is safe for redirects.
            # See http://flask.pocoo.org/snippets/62/ for an example.
            if not is_safe_url(next):
                return flask.abort(400)

            return flask.redirect(next or flask.url_for('index'))
        return flask.render_template('login.html', form=form)

    @app.route('/logout')
    def showLogout():

        logout_user()
        flask.flash('Logged out successfully.')

        return 'Logged out'

    ##########################
    # General Administration #
    ##########################

    @app.before_request
    def force_https():
        """
        Redirect from http to https
        """
        if os.environ.get('DATABASE_URL') is not None:
            if not request.is_secure:
                url = request.url.replace('http://', 'https://', 1)
                code = 301
                return redirect(url, code=code)

    ##################
    # JSON API calls #
    ##################

    @app.route('/suppliers/JSON')
    @login_required
    def showSuppliersJSON():
        """
        Return order data in JSON
        """
        suppliers = Supplier.query.all()

        return jsonify(suppliers_schema.dump(suppliers).data)

    @app.route('/shippers/JSON')
    @login_required
    def showShippersJSON():
        """
        Return order data in JSON
        """
        shippers = Shipper.query.all()

        return jsonify(shippers_schema.dump(shippers).data)

    @app.route('/products/JSON')
    @login_required
    def showProductsJSON():
        """
        Return order data in JSON
        """
        products = Product.query.all()

        return jsonify(products_schema.dump(products).data)

    @app.route('/orders/JSON')
    @login_required
    def showOrdersJSON():
        """
        Return order data in JSON
        """
        orders = Order.query.all()

        return jsonify(orders_schema.dump(orders).data)

    @app.route('/orders/unfulfilled/JSON')
    @login_required
    def showUnfulfilledOrdersJSON():
        """
        Return unfulfilled order data in JSON
        """
        unful_orders = Order.query.filter_by(wasOrdered=False).all()

        return jsonify(orders_schema.dump(unful_orders).data)

    @app.route('/customers/JSON')
    @login_required
    def showCustomersJSON():
        """
        Return customer data in JSON
        """
        customers = Customer.query.all()

        return jsonify(customers_schema.dump(customers).data)

    #######################
    # Client facing pages #
    #######################

    @app.route('/orders')
    @login_required
    def showOrders():
        """
        Display the supplier - facing orders page. The supplier can accept
        the job, then is directed to the showAcceptOrder
        """
        unaccepted_orders = Order.query.filter_by(wasAccepted=False).all()

        session['supplier'] = current_user.email

        return render_template('auth/unassigned_orders.html', orders=unaccepted_orders)

    @app.route('/orders/<int:order_id>/accepted', methods=['GET', 'POST'])
    @login_required
    def showAcceptOrder(order_id):
        """
        Display the supplier-facing order accepted page.
        """
        order = Order.query.filter_by(orderID=order_id).first()
        supplier = Supplier.query.filter_by(
            email=session['supplier']).first()
        selected_order = Order.query.filter_by(orderID=order_id).first()
        selected_order_details = OrderDetails.query.filter_by(
            order_ID=order_id).first()
        supplier_id = supplier.supplierID

        order.wasAccepted = True
        selected_order.supplier_ID = supplier_id
        db.session.add(selected_order)
        db.session.commit()
        return render_template('auth/selected_order.html', order=selected_order_details)

    @app.route('/', methods=["GET", "POST"])
    @app.route('/home')
    @cache.cached(timeout=86400)
    def showHome():
        """
        Display the landing page.
        """
        return render_template('home.html')

    @app.route('/about')
    @cache.cached(timeout=86400)
    def showAbout():
        """
        Display the About Us page.
        """
        return render_template('about.html')

    @app.route('/design', methods=['GET', 'POST'])
    @cache.cached(timeout=86400)
    def showDesign():
        """
        Display a kokeshi designing page that, when submitted, updates the shopping cart with the order and redirects to the order page.
        """
        # Create a new cart list.
        if 'cart' not in session:
            session['cart'] = []

        if request.method == 'POST':
            # Create a customer object without an email, to attach to the cart
            # items in the session.
            customer = Customer(email="")
            db.session.add(customer)
            db.session.commit()

            # Create an order object and tie it to the customer.
            order = Order(customer_ID=customer.customerID)
            db.session.add(order)
            db.session.commit()

            product = Product.query.filter_by(
                name=request.form['item']).one()

            # Assign the order to the customer using the orderID
            customer.order_ID = order.orderID

            if request.form.get('is-message', False) == 'on':
                order_details = OrderDetails(
                    item=request.form['item'],
                    name=request.form['name'],
                    dob=request.form['dob'],
                    height=request.form['height'],
                    weight=request.form['weight'],
                    is_message=True,
                    message=request.form['message'],
                    order_ID=order.orderID,
                    customer_ID=customer.customerID,
                    product_ID=product.productID
                )

            else:
                order_details = OrderDetails(
                    item=request.form['item'],
                    name=request.form['name'],
                    dob=request.form['dob'],
                    height=request.form['height'],
                    weight=request.form['weight'],
                    is_message=False,
                    order_ID=order.orderID,
                    customer_ID=customer.customerID,
                    product_ID=product.productID
                )

            # Set the price of the item, dependent on the presence or absence of a message.
            if request.form.get('is-message', False) == 'on':
                price = 250
            else:
                price = 200

            order.price = price

            db.session.add(customer)
            db.session.add(order)
            db.session.add(order_details)
            db.session.commit()

            # Append the item to the cart.
            session['cart'].append(
                {
                    'itemID': order_details.orderDetailsID,
                    'item': order_details.item,
                    'name': order_details.name,
                    'dob': order_details.dob,
                    'height': order_details.height,
                    'weight': order_details.weight,
                    'isMessage': order_details.is_message,
                    'message': order_details.message,
                    'product': product.name,
                    'price': price,
                    'orderID': order_details.order_ID
                }
            )

            # Create a session variable to select the customer in order to append information.
            session['customer_ID'] = customer.customerID

            flash("Success! Your order for '%s kokeshi' has been added to your cart." %
                  order_details.name)

            return redirect(url_for('showOrder'))

        else:
            return render_template('design.html')

    @app.route('/setCart')
    def setCart():
        cartObj = session['cart']
        cartJSON = jsonify(cartObj)
        return cartJSON

    @app.route('/removeItem/<int:item_id>', methods=["GET", "POST"])
    def removeItem(item_id):
        """
        Remove the selected item from the cart.
        """
        # Check for the existence of an item, then convert it to an int
        if item_id is not None:
            item_id = int(item_id)

        try:
            session['cart'][:] = [d for d in session['cart']
                                  if d.get('itemID') != item_id]
        except:
            msg = "There were no items to remove"
            print(msg)
        return redirect(url_for('showOrder'))

    @app.route('/order', methods=["GET", "POST"])
    def showOrder():
        """
        Display the order page - - a list of all the items in the cart.
        """

        return render_template('order.html')

    @app.route('/checkout', methods=['GET', 'POST'])
    def showCheckout():
        """
        Display the checkout page, which displays the total and a Stripe payments button.
        """
        amount_usd = 0

        # Add up the total of all the items in the cart
        for item in session['cart']:
            amount_usd += item['price']

        # Calculate the amount in US cents for Stripe
        amount_cents = amount_usd * 100

        return render_template(
            'auth/index.html',
            key=stripe_keys['publishable_key'],
            amount_usd=amount_usd,
            amount_cents=amount_cents,
            cart=session['cart']
        )

    @app.route('/charge', methods=['GET', 'POST'])
    def charge():
        db_customer = Customer.query.filter_by(
            customerID=session['customer_ID']).one()
        # Amount in cents
        amount = 0
        items = []
        for item in session['cart']:
            # Add the item prices in cents.
            amount += item['price'] * 100
            items.append(item['item'])

        customer = stripe.Customer.create(
            email=request.form['stripeEmail'],
            source=request.form['stripeToken']
        )

        # Create a session variable with the customer's email for sending a
        # confirmation email.
        session['customer_email'] = request.form['stripeEmail']

        # Create a Stripe charge object which sends a confirmation email.
        charge = stripe.Charge.create(
            customer=customer.id,
            amount=amount,
            currency='usd',
            description='KokeMama Charge',
            receipt_email=session['customer_email']
        )

        # Attempt to add customer data from the stripe input to the customer
        # object
        try:
            db_customer.email = request.form['stripeEmail']
        except:
            print("There is no 'stripeEmail' key")
        try:
            db_customer.name = charge.source.name
        except:
            print("There is no 'stripeName' key")
        try:
            db_customer.address1 = charge.source.address_line1
        except:
            print("There is no 'stripeShippingAddressLine1' key")
        try:
            db_customer.zipCode = charge.source.address_zip
        except:
            print("There is no 'stripeShippingAddressZip' key")
        try:
            db_customer.state = charge.source.address_state
        except:
            print("There is no 'stripeShippingAddressState' key")
        try:
            db_customer.city = charge.source.address_city
        except:
            print("There is no 'stripeShippingAddressCity' key")
        try:
            db_customer.country = charge.source.address_country
        except:
            print("There is no 'stripeShippingAddressCountry' key")

        db.session.add(db_customer)
        db.session.commit()

        return redirect(url_for('showConfirm'))

    @app.route('/confirmation')
    def showConfirm():
        """
        Display the order confirmation page after an order is submitted.
        """
        # Get the customer from the db using the 'customer_ID' session variable
        db_customer = Customer.query.filter_by(
            customerID=session['customer_ID']).one()

        # Create a list of the cart items for use in the email's message body
        items = [dic['item'] for dic in session['cart'] if 'item' in dic]

        # Use the first item in the cart to obtain the 'orderID'. If None,
        # display 'design' link
        try:
            firstItem = session['cart'][0]
            orderID = firstItem['orderID']

            msg = Message(
                'Confirmation', sender='*****@*****.**', recipients=[session['customer_email']])
            msg.body = "Thank you for your order of: %s. Your order number is: %d." % (
                items, orderID)
            mail.send(msg)

            # Clear the cart after payment is received and confirmation is sent.
            session['cart'] = []

            return render_template('auth/confirmation.html')
        except:
            return redirect(url_for('showHome'))

    @app.route('/contact', methods=['GET', 'POST'])
    @cache.cached(timeout=86400)
    def showContact():
        """
        Display the contact information page.
        """
        if request.method == 'POST':
            msg = Message(
                'Contact', sender='*****@*****.**', recipients=['*****@*****.**'])
            msg.body = "Customer name: %s\n" % (
                request.form['customer-name'])
            msg.body += "Customer email: %s\n" % (
                request.form['customer-email'])
            msg.body += "Message: %s" % (request.form['customer-message'])
            mail.send(msg)

            customer = Customer(
                name=request.form['customer-name'],
                email=request.form['customer-email']
            )
            db.session.add(customer)
            db.session.commit()
            return redirect(url_for('showContactComplete'))

        else:
            return render_template('contact.html')

    @app.route('/contact/complete')
    def showContactComplete():
        """
        Show a success message for the contact form.
        """
        return render_template('auth/contact_complete.html')

    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)
    heroku.init_app(app)
    mail.init_app(app)

    # Load the current logged in user.
    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    return app
Esempio n. 21
0
def register_extensions_test(app):
    cors.init_app(app, supports_credentials=True)
    jwt.init_app(app)
    csrf.init_app(app)

    return None
Esempio n. 22
0
def register_extensions(app):
    csrf.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    moment.init_app(app)
Esempio n. 23
0
def create_app():
    app = Flask(__name__)

    # 初始化配置
    app.config.from_object(config)
    config.init_app(app)
    config_logging(app)

    # db配置
    db.init_app(app)

    # mongo
    mongo.init_app(app)

    # 控制器配置
    from controllers import default_blueprints
    for blueprint in default_blueprints:
        app.register_blueprint(blueprint)

    # 开启 CsrfProtect 模块
    csrf.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        from models import User
        user = db.session.query(User).get(int(user_id))
        user.nickname = user.to_dict()['nickname']
        return user

    login_manager.init_app(app)
    # cookie有效期
    app.permanent_session_lifetime = datetime.timedelta(minutes=24 * 60)
    login_manager.remember_cookie_duration = datetime.timedelta(days=1)

    # 访问静态资源
    def public_file(filename):
        return send_from_directory(app.config.get("UPLOAD_FOLDER"), filename)

    app.add_url_rule("/public/<filename>", "public_file", build_only=True)

    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {"/public": app.config.get("UPLOAD_FOLDER")},
        cache=False
        # tips: http://stackoverflow.com/questions/11515804/zombie-shareddatamiddleware-on-python-heroku
    )

    # favicon.ico
    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(app.static_folder,
                                   'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    # Robots
    @app.route('/robots.txt')
    def robots():
        return send_from_directory(app.static_folder, 'robots.txt')

    # sitemap.xml
    @app.route('/sitemap<name>')
    def sitemap(name):
        return send_from_directory(app.static_folder, 'sitemap%s' % name)

    # 过滤器处理
    configure_template_filters(app)

    # 错误处理
    configure_error_handlers(app)

    return app
Esempio n. 24
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    csrf.exempt(api_v1)
    babel.init_app(app)
Esempio n. 25
0
def register_extensions(app):
    db.init_app(app)
    csrf.init_app(app)