Example #1
0
def create_app(username, password, matrikkel_url, matrikkel_user, matrikkel_pass):
    app = Flask(__name__)

    app.config['BASIC_AUTH_FORCE'] = True
    app.config['BASIC_AUTH_USERNAME'] = username
    app.config['BASIC_AUTH_PASSWORD'] = password

    create_api(app, API_VERSION, matrikkel_url, matrikkel_user, matrikkel_pass)
    if not app.debug:
        stream_handler = StreamHandler()
        app.logger.addHandler(stream_handler)

    return app
    def setUp(self):
        app = Flask(__name__)

        app.config['BASIC_AUTH_USERNAME'] = 'john'
        app.config['BASIC_AUTH_PASSWORD'] = 'matrix'

        basic_auth = BasicAuth(app)

        @app.route('/')
        def normal_view():
            return 'This view does not normally require authentication.'

        @app.route('/protected')
        @basic_auth.required
        def protected_view():
            return 'This view always requires authentication.'

        self.app = app
        self.basic_auth = basic_auth
        self.client = app.test_client()
Example #3
0
def create_app(cfg):
    """
    Application factory function

    :param cfg: dict
        Configuration parameters

    :return: app
    """
    app = Flask(__name__)

    from . api import api

    app.register_blueprint(api)

    # By default this sets CORS access to resource endpoints to `*`
    app.config['BASIC_AUTH_USERNAME'] = cfg['api']['username']
    app.config['BASIC_AUTH_PASSWORD'] = cfg['api']['password']

    # Enable CORS Configuration and Basic Authentication
    cors       = CORS(app)
    api        = Api(app)

    return app
Example #4
0
def create_app(sqlite_path='sqlite:///intent.db'):
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = sqlite_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['BASIC_AUTH_USERNAME'] = 'john'
    app.config['BASIC_AUTH_PASSWORD'] = 'matrix'
    babel = Babel(app)
    admin = Admin(app, name='PrayerBot', template_mode='bootstrap3')
    db.init_app(app)
    register_admin(admin, app)
    app.app_context().push()

    app.add_url_rule('/webhook', view_func=WebhookAPI.as_view('webhook'))
    app.add_url_rule('/privacy', view_func=PrivacyPolicy.as_view('privacy'))

    if os.environ.get('ACCESS_TOKEN'):
        utils.send_greeting_text_config()

    db.create_all()
    db.session.commit()
    db.session.autoflush = True
    db.session.autocommit = True

    return app
Example #5
0
from flask import Flask
from flask_login import LoginManager
from datetime import timedelta
import os
from flask.ext.basicauth import BasicAuth
from flask.ext.mongoengine import MongoEngine

UPLOAD_FOLDER = os.getcwd() + '/uploads/'

app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = 'radteam'
app.config['BASIC_AUTH_PASSWORD'] = 'rad0109'
app.config['DEBUG']=True
basic_auth = BasicAuth(app)

login_manager = LoginManager()
login_manager.init_app(app)
app.secret_key = 'putyoursecretkey'
app.permanent_session_lifetime = timedelta(seconds=600)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

from .urls import *
Example #6
0
import os, sys
from flask import Flask, render_template, request, redirect, url_for
from flask.ext.basicauth import BasicAuth
from werkzeug import secure_filename
from os import path
 
app = Flask(__name__)      

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['gpx'])

app.config['BASIC_AUTH_USERNAME'] = 'hawaii'
app.config['BASIC_AUTH_PASSWORD'] = 'trails'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def track_list():
  path = os.getcwd() + "/static/gpx/"
  files = []
  dirs = os.listdir( path )
  for file in dirs:
     files.append(file)
  return files
track_list = track_list()

@app.route('/')
def index():
  return render_template('layout.html', files=track_list)

basic_auth = BasicAuth(app)
Example #7
0
from flask.ext.basicauth import BasicAuth
from openfecwebapp.views import (render_search_results, render_table,
    render_page)
from openfecwebapp.api_caller import (load_search_results,
    load_single_type, load_single_type_summary,
    install_cache)

import sys
import locale
locale.setlocale(locale.LC_ALL, '')

app = Flask(__name__)

app.jinja_env.globals['api_location'] = api_location

app.config['BASIC_AUTH_USERNAME'] = username
app.config['BASIC_AUTH_PASSWORD'] = password
app.config['BASIC_AUTH_FORCE'] = True

basic_auth = BasicAuth(app)

def _convert_to_dict(params):
    """ move from immutablemultidict -> multidict -> dict """
    params = params.copy().to_dict()
    params = {key: value for key, value in params.items() if value}
    return params

@app.route('/')
def search():
    query = request.args.get('search')
    if query:
from flask import Flask
from flask.ext.basicauth import BasicAuth

app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'secret'

basic_auth = BasicAuth(app)


@app.route('/')
@basic_auth.required
def index():
    return "Flask Index Page"

if __name__ == '__main__':
    app.run()
Example #9
0
from flask import Flask
from flask import jsonify
from flask import make_response
from flask.ext.basicauth import BasicAuth

app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = 'app99'
app.config['BASIC_AUTH_PASSWORD'] = 'pass99'

basic_auth = BasicAuth(app)

shows = [
	{
		"sid": 3001,
		"name": "Breaking Bad",
		"rating": "9.4"
	},
	{
		"sid": 3002,
		"name": "Dexter",
		"rating": "9.0"
	}
]

@app.route('/shows/<int:show_id>')
@basic_auth.required
def get_show(show_id):
	search = filter(lambda s: s['sid'] == show_id, shows)
	if len(search) == 0:
		return make_response(jsonify({'error': 'Show not found'}), 404)
Example #10
0
import pycurl
import re
import StringIO
import string

# configuration
DATABASE = '/tmp/insta.db'
DEBUG = True
SECRET_KEY = 'LKDNF(ln3r(sj3r9JIWJ(j(JP#!N(J@91-93jn'
USERNAME = 'admin'
PASSWORD = 'default'

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('INSTA_SETTINGS', silent=True)
app.config['BASIC_AUTH_USERNAME'] = 'emojimilan'
app.config['BASIC_AUTH_PASSWORD'] = 'circlecracker'

basic_auth = BasicAuth(app)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
LIKES_FOLDER = os.path.join(APP_ROOT, 'static/like/')
SUPER_FOLDER = os.path.join(APP_ROOT, 'static/super/')
EDITED_SUPER_FOLDER = os.path.join(APP_ROOT, 'static/edited_super/')
app.config['like'] = LIKES_FOLDER
app.config['super'] = SUPER_FOLDER
app.config['edited_super'] = EDITED_SUPER_FOLDER
SCREEN_TOTAL = 2

jsglue = JSGlue(app)
socketio = SocketIO(app)
Example #11
0
@app.route('/ssgs', methods=['POST']) 
def getSSG():
    content = request.get_json(silent=False)
    requiredFields = {'ssgFile', 'tailoringFile' }
    if content is None:
        return '{ "Error" : "json data required" }', 400
    elif not requiredFields <= set(content):
        return '{ "Error": "There are missing fields in the request" }', 400
    elif content['ssgFile'] == "":
        return '{ "Error": "ssgFile field cannot be empty" }', 400
    else:
        response = oscapd.get_ssg(content['ssgFile'],content['tailoringFile'])
        return response

if __name__ == "__main__":
    oscapd = OScapDaemonApi()
    config = configparser.ConfigParser()
    config.read('config.ini')
    c_debug = config.getboolean('Api','debug')
    c_host = config.get('Api','host')
    c_port = config.get('Api','port')
    c_auth = config.getboolean('Api','auth')
    if c_auth:
      basic_auth = BasicAuth(app)
      app.config['BASIC_AUTH_USERNAME'] = config.get('Api','username')
      app.config['BASIC_AUTH_PASSWORD'] = config.get('Api','password')
      app.config['BASIC_AUTH_FORCE'] = True
    # Uncomment when testing
    app.debug = c_debug
    app.run(host=c_host, port=c_port)
Example #12
0
#!/usr/bin/python3
from flask import Flask, session, redirect, escape, request, render_template, url_for
from flask_socketio import SocketIO
import os
import argparse
import sys
from arm_interface import ArmInterface
from flask.ext.basicauth import BasicAuth
# import uuid
import players
from werkzeug.routing import RequestRedirect

app = Flask(__name__, static_folder="static")
# Auth
app.config['BASIC_AUTH_USERNAME'] = 'john'
app.config['BASIC_AUTH_PASSWORD'] = 'matrix'
basic_auth = BasicAuth(app)
socketio = SocketIO(app)

# Connect to Arm
arm = ArmInterface()
arm.begin_connection()

global_list = {}

current_players = players.Players()


# Routing
@app.route("/")
def home():
Example #13
0
import os
import aikif.cls_log as mod_log
import aikif.config as mod_cfg

lg = mod_log.Log(mod_cfg.fldrs['log_folder'])
lg.record_command('api_main', 'starting API server in ' + os.getcwd())

from flask import Flask, jsonify, abort, make_response
from flask.ext.restful import Api, Resource, reqparse, fields, marshal
from flask.ext.httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path="")
api = Api(app)
auth = HTTPBasicAuth()

app.config['BASIC_AUTH_USERNAME'] = 'local'
app.config['BASIC_AUTH_PASSWORD'] = 'local'

base_url = '/aikif/api/v1.0/'    # http://127.0.0.1:5000/aikif/api/v1.0/facts/2
base_url = '/aikif/api/v2.0/'
base_url = '/'                   # http://127.0.0.1:5000/facts/2
url_pre = 'http://127.0.0.1:5000' 
#basic_auth = BasicAuth(app)


@auth.get_password
def get_password(username):
    if username == 'local':
        return 'local'
    return None
Example #14
0
# Copyright 2015 elastic-search-api authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

import json
import os
import requests
from flask import Flask, request
from flask.ext.basicauth import BasicAuth


app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = os.environ.get("ES_BROKER_USERNAME", 'admin')
app.config['BASIC_AUTH_PASSWORD'] = os.environ.get("ES_BROKER_PASSWORD", 'password')

basic_auth = BasicAuth(app)
app.config['BASIC_AUTH_FORCE'] = True

ELASTICSEARCH_HOST = os.environ.get("ELASTICSEARCH_HOST")
ELASTICSEARCH_PORT = os.environ.get("ELASTICSEARCH_PORT", '9200')


@app.route("/resources/plans", methods=["GET"])
def plans():
    plans = [{"name": "shared_data", "description": "shared elasticsearch server"}]
    return json.dumps(plans), 200


@app.route("/resources", methods=["POST"])
def add_instance():
Example #15
0
import os

from flask import abort, Flask, jsonify, redirect, render_template, request
from flask.ext.basicauth import BasicAuth

from .filekeeper import delete_files, insert_link_to_latest, parse_docfiles, unpack_project
from . import getconfig

app = Flask(__name__)

app.config['MAX_CONTENT_LENGTH'] = getconfig.max_content_mb * 1024 * 1024
app.config['BASIC_AUTH_USERNAME'] = 'kimono'
app.config['BASIC_AUTH_PASSWORD'] = 'prrrok123'
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)


@app.route('/hmfd', methods=['POST', 'DELETE'])
def hmfd():
    if getconfig.readonly:
        return abort(403)

    if request.method == 'POST':
        if not request.files:
            return abort(400, 'Request is missing a zip file.')
        unpack_project(
            request.files.values()[0].stream,
            request.form,
            getconfig.docfiles_dir)
    else:
        assert request.method == 'DELETE'
Example #16
0
from flask import Flask, make_response, render_template, request, redirect, url_for
import collect_follower_count
import turk_functions
import collect_like_decay
from flask.ext.basicauth import BasicAuth
from hashlib import sha512
import datetime as dt

app = Flask(__name__)
app.secret_key = sha512("cybersec").hexdigest()
app.config['BASIC_AUTH_USERNAME'] = 'groupthinkmanager'
app.config['BASIC_AUTH_PASSWORD'] = 'accounts'

env = app.jinja_env
env.line_statement_prefix = '='

basic_auth = BasicAuth(app)

@app.route('/', methods = ["GET", "POST"])
@basic_auth.required
def index():
    if request.method == "POST":
        if 'account_list' in request.form:
            raw_account_string = request.form['account_list']
            if raw_account_string != "":
                account_list = request.form['account_list'].split(",")
                for account in account_list:
                    collect_follower_count.add_username(account)
        elif 'like_account_list' in request.form:
            raw_account_string = request.form['like_account_list']
            if raw_account_string != "":
Example #17
0
from flask.ext.basicauth import BasicAuth

# Project imports
import config
import dbsetup
from cors import corsify

# Set up database
client, database = dbsetup.dbsetup()

# Initialize app
app = Flask(__name__)
app.config['DEBUG'] = True

# 
app.config['BASIC_AUTH_USERNAME'] = os.environ.get('CITELET_AUTH_USERNAME')
app.config['BASIC_AUTH_PASSWORD'] = os.environ.get('CITELET_AUTH_PASSWORD')

# 
basic_auth = BasicAuth(app)

# 
here = os.path.split(__file__)[0]

def request_to_ip(req):
    """ Grab user IP address from flask request object. """
    
    if not request.headers.getlist("X-Forwarded-For"):
       return request.remote_addr
    return request.headers.getlist("X-Forwarded-For")[0] 
Example #18
0
from flask import Flask, render_template, request, url_for, json, redirect, flash
from flask.ext.basicauth import BasicAuth
import random
import string
from utils import *
import os
import sqlite3

app = Flask(__name__)

# setup authentification
app.config['BASIC_AUTH_USERNAME'] = 'metjush'
app.config['BASIC_AUTH_PASSWORD'] = 'totojemojepydgetheslo'

basic_auth = BasicAuth(app)

# setup database connection

N = 64
app.secret_key = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(N))


@app.route('/')
@basic_auth.required
def index():
    """
    Load the budget
    Display current month status
    :return: template
    """
    app.config['budget'] = url_for('static', filename='budget.json')
Example #19
0
from flask.ext.basicauth import BasicAuth
import MySQLdb
import collections
from logging.handlers import RotatingFileHandler
import json
import ast
from datetime import *
from types import *
#
sys.path.insert(0, './static/python')
from socool_utils import *
from forms import opdDeploymentForm

app = Flask(__name__)
app.config.from_object('config')
app.config['BASIC_AUTH_USERNAME'] = 'oceantech'
app.config['BASIC_AUTH_PASSWORD'] = 'm0t3_ot'
basic_auth = BasicAuth(app)

#routes
@app.route('/login/opd/deploy/update', methods=['POST'])
@basic_auth.required
def update():

    conn = connect_db_socool()
    cursor =  conn.cursor(MySQLdb.cursors.DictCursor)

    serial = int(request.form['serial'])
    operator = request.form['operator']
    deployed = request.form['deployed']
    site = request.form['site']
Example #20
0
from flask import Flask, render_template, url_for, request, Response, redirect, flash, jsonify, make_response
from flask import session as motorSwitch
from flask.ext.basicauth import BasicAuth
from datetime import timedelta
from flask import make_response, request, current_app
import motor
import os
from thread import start_new_thread
from flask.ext.cors import CORS
import subprocess
import requests

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
APPLICATION_NAME = "mikeBot"
app.config['BASIC_AUTH_USERNAME'] = 'test'
app.config['BASIC_AUTH_PASSWORD'] = 'test'

basic_auth = BasicAuth(app)

def startStream():

    subprocess.call('export LD_LIBRARY_PATH=. ; ./mjpg_streamer -o "output_http.so -w ./www" -i "input_raspicam.so -x 640 -y 480 -fps 15 -vf -hf"', shell=True, cwd='/var/www/mjpg-streamer/mjpg-streamer-experimental')

@app.route('/', methods=['GET','POST'])
@basic_auth.required
def front():

    motorSwitch["right"] = 0
    motorSwitch["left"] = 0
    myIP = requests.get('https://api.ipify.org').text
Example #21
0
from flask import Flask
from flask import request
from flask.ext.basicauth import BasicAuth
import boto.ses
import os

app = Flask(__name__)
app.config['DEBUG'] = True

app.config['BASIC_AUTH_USERNAME'] = os.environ['USER']
app.config['BASIC_AUTH_PASSWORD'] = os.environ['PASSWORD']

basic_auth = BasicAuth(app)

@app.route('/message')
@basic_auth.required
def message():
    subject = "Text Message from %s" % request.args.get('From')
    content = "Body: %(body)s \nMedia: %(url)s" % {"body": request.args.get('Body'), "url":request.args.get('MediaUrl0')}
    send_mail(subject, content)
    return("", 200)

def send_mail(subject, content):
    conn = boto.ses.connect_to_region(
            'us-east-1',
            aws_access_key_id=os.environ['AWS_ACCESS_KEY'],
            aws_secret_access_key=os.environ['AWS_SECRET_KEY'])
    conn.send_email(
            'team@gopartage.com',
            subject,
            content,
Example #22
0
        'client_secret': CLIENT_SECRET,
        }
    r = requests.post('https://coinbase.com/oauth/token', data=access_token_data)
    if r.status_code == 200:  # Request was successful, output access token and return it.
        #token_data = json.loads(r.text)
        return str(json.loads(r.text)['access_token'])
    else:
        print 'There was an error retrieving the access_token'
        print r.text


# Setup Flask Webserver
app = Flask(__name__)

# Authentication for live instance
app.config['BASIC_AUTH_USERNAME'] = 'coinbase'
app.config['BASIC_AUTH_PASSWORD'] = 'securityP0C'
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)

@app.route('/')
@basic_auth.required
def index():
    # Retrieve authorization form and return it to the user
    return render_template('index.html', oauthform=retrieveOAuthForm(OAUTH_URL, cookie).decode('utf-8'))


# Retrieve the code token from the callback, get the access token and make some tests.
@app.route('/callback')
@basic_auth.required
def callbackPage():
Example #23
0
File: app.py Project: hancush/sadi
import re
import os

from flask import Flask, render_template, request, jsonify, url_for, session
from flask.ext.basicauth import BasicAuth
from flask_weasyprint import HTML, render_pdf
from slacker import Slacker

from classes_web import Parser

app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = os.environ['username']
app.config['BASIC_AUTH_PASSWORD'] = os.environ['pass']

basic_auth = BasicAuth(app)

@app.route('/',methods=['GET', 'POST'])
def listen():
    data = request.form
    if data['token'] == os.environ['ap_token']:
        story = re.sub(' ', '_', data['text']) # handle special chars (punctuation, etc.)
        url = 'https://here-sadi.herokuapp.com/{0}_report.pdf'.format(story)
        return jsonify({'response_type': 'ephemeral',
                        'text': ':confetti_ball: Here\'s your PDF: {0} :confetti_ball:'.format(url)})
    else:
        print 'no'
        return jsonify({'response_type': 'ephemeral',
                        'text': 'Girls are cool but your request wasn\'t. :upside_down_face:'})

@app.route('/<story>_report.pdf')
Example #24
0
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, make_response, g, Response, url_for, flash, redirect, abort
from flask.ext.basicauth import BasicAuth
from jinja2 import evalcontextfilter, Markup, escape

from datetime import datetime, timedelta
from functools import wraps
import models
import settings
import re

app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = settings.username
app.config['BASIC_AUTH_PASSWORD'] = settings.password
app.config['BASIC_AUTH_REALM'] = 'Welcome to the admin page'
app.secret_key = settings.secret_key

basic_auth = BasicAuth(app)

# Disconnet to the database
@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

# Session decorater
def session_wrapper(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        models.start_session()
Example #25
0
File: main.py Project: uovobw/pyql
#local imports
from DbSchema import DbSchema

app = Flask(__name__)
app.debug = True

app.config.update(
    DB_HOST="127.0.0.1",
    DB_USER="root",
    DB_PASSWORD="hackme",
    DB_NAME="employees",
    DB_PORT="3306"
)

app.config['BASIC_AUTH_USERNAME'] = 'user'
app.config['BASIC_AUTH_PASSWORD'] = 'password'

basic_auth = BasicAuth(app)


@app.route('/')
@basic_auth.required
def root():
    return 'Hello'


@app.route("/columns/<t>")
@basic_auth.required
def get_column(t):
    return ",".join(app.config['SCHEMA'].getColumns(t))
Example #26
0
from messenger import Locator
locator = Locator(app)

from flask.ext.mail import Mail
mail = Mail()
mail.init_app(app)

from flask.ext.security import (
    Security,
    MongoEngineUserDatastore
)

from .models import User, Role
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore)

from www import views

from www.greenpaper.views import paper
app.register_blueprint(paper)

from flask.ext.basicauth import BasicAuth
http_basic_user = os.environ.get('BASIC_AUTH_USERNAME')
http_basic_password = os.environ.get('BASIC_AUTH_PASSWORD')
if http_basic_user and http_basic_password:
    app.config['BASIC_AUTH_USERNAME'] = http_basic_user
    app.config['BASIC_AUTH_PASSWORD'] = http_basic_password
    app.config['BASIC_AUTH_FORCE'] = True
    basic_auth = BasicAuth(app)
Example #27
0
# https://flask-basicauth.readthedocs.org/en/latest/
# https://flask-restful.readthedocs.org/en/latest/index.html
# https://github.com/miguelgrinberg/REST-auth
# https://github.com/miguelgrinberg/REST-tutorial/blob/master/rest-server-v2.py

from flask import Flask, request, make_response, jsonify, abort
from flask_restful import Resource, Api, reqparse
from flask.ext.basicauth import BasicAuth
import json
from sqlalchemy import create_engine

db = create_engine('sqlite:///servers.db')
app = Flask(__name__)
api = Api(app)
app.config['BASIC_AUTH_USERNAME'] = 'demo'
app.config['BASIC_AUTH_PASSWORD'] = 'demo'
basic_auth = BasicAuth(app)


def router_exists(router):
	conn = db.connect()
	query = conn.execute("select count(*) from servers where server='%s'" % router.lower()).fetchone()
	if query[0] == 1:
		return True

# PUBLIC API QUERIES
class All(Resource): # returns the full list of routers
	def get(self):
		conn = db.connect()
		query = conn.execute("select server,port,type from servers")
		return {'servers': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
Example #28
0
from flask import Flask, request, redirect, url_for, send_from_directory, render_template
from flask.ext.basicauth import BasicAuth
from datetime import date

import sys
import os

from peewee import *

db = SqliteDatabase(sys.argv[3])

app = Flask(__name__)
app.debug = True

app.config['BASIC_AUTH_USERNAME'] = sys.argv[1]
app.config['BASIC_AUTH_PASSWORD'] = sys.argv[2]

basic_auth = BasicAuth(app)

# Set up some objects for or ORM
class IDCard(Model):
  first    = CharField()
  last     = CharField()
  cardsite = IntegerField()
  cardnum  = IntegerField()
  front    = BooleanField()
  back     = BooleanField()
  wood     = BooleanField()
  metal    = BooleanField()
  
  class Meta:
Example #29
0
from flask import jsonify
import os
import database

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

# if on heroku, then set debug to false
if 'DYNO' in os.environ:
  app.config['DEBUG'] = False

# if on heroku, then password protect entire site
if 'DYNO' in os.environ:
  from flask.ext.basicauth import BasicAuth
  app.config['BASIC_AUTH_USERNAME'] = app.config.get('USERNAME')
  app.config['BASIC_AUTH_PASSWORD'] = app.config.get('PASSWORD')
  app.config['BASIC_AUTH_FORCE'] = True
  basic_auth = BasicAuth(app)

# Get constants
app.debug = app.config.get('DEBUG')
app.secret_key = os.environ.get('SECRET_KEY',
    app.config.get('LOCAL_SECRET_KEY'))

# Register blueprints
app.register_blueprint(auth, url_prefix='/auth')

# Add useful functions to 
app.jinja_env.globals.update(is_authenticated=is_authenticated)
Example #30
0
from flask import Flask, render_template, jsonify, request, redirect
from flask.ext.basicauth import BasicAuth
import texting, config, db

app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = config.auth_u
app.config['BASIC_AUTH_PASSWORD'] = config.auth_p
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)

@app.route("/")
def hello():
  try:
    subs = db.get_allphonenumbers()
  except Exception as e:
    return redirect(url_for('hello'))

  return render_template("index.html", subscribers=subs)

@app.route("/go", methods=["POST"])
def post_msg():
  msg = request.form.getlist("text_msg")
  if texting.send_text(msg):
    jsonstring = {"Message":msg[0], "Success":True}
    return jsonify(jsonstring)
  else:
    jsonstring = {"Message":msg[0], "Success":False}
    return jsonify(jsonstring)

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