Пример #1
0
    def post(self):
        db_sess = db_session.create_session()
        try:
            data = loads(request.get_data())
            validate(instance=data, schema=ADD_SCHEMA)
            token = data.pop('token')
            user = db_sess.query(User).filter(User.token == token)[0]
            data['time'] = dt.strptime(data['time'], "%H:%M").time()
            data['day'] = dt.strptime(data['day'], "%m-%d-%Y").date()
            assert user

        except AssertionError:
            data = dumps({"error": "Неверный токен"})
            response = Flask.response_class(status=403,
                                            mimetype="application/json",
                                            response=data)
            return response

        except Exception as e:
            data = dumps({"error": str(e)})
            response = Flask.response_class(status=400,
                                            mimetype="application/json",
                                            response=data)
            return response

        data['owner_id'] = user.id
        table = Tables(**data)
        db_sess.add(table)
        db_sess.commit()
        db_sess.close()
        response = Flask.response_class(status=200)
        return response
Пример #2
0
    def get(self):
        db_sess = db_session.create_session()
        try:
            data = loads(request.get_data())
            validate(instance=data, schema=LIST_SCHEMA)
            token = data.pop('token')
            user = db_sess.query(User).filter(User.token == token)[0]
            start = dt.strptime(data['start'], "%d-%m-%Y").date()
            end = dt.strptime(data['end'], "%d-%m-%Y").date()
            assert user

        except AssertionError:
            data = dumps({"error": "Неверный токен"})
            response = Flask.response_class(status=403,
                                            mimetype="application/json",
                                            response=data)
            return response

        except Exception as e:
            data = dumps({"error": str(e)})
            response = Flask.response_class(status=400,
                                            mimetype="application/json",
                                            response=data)
            return response
        response = list()
        for obj in db_sess.query(Tables).filter(Tables.day.between(start,
                                                                   end)):
            response.append(obj.to_dict())
        print(response)
        response = dumps(response)

        response = Flask.response_class(status=400,
                                        mimetype="application/json",
                                        response=response)
        return response
Пример #3
0
    def make_response(self, data, status_code, headers):
        if not data:
            Flask.response_class(
                "",
                mimetype=self.mimetype
            ), status_code, headers

        # if the status code is not a success code
        if status_code % 100 == 4 and self.error_type:
            response_data = self.error_type()
        else:
            if not self.send_type:
                raise EncodeError(
                    "Data could not be encoded into a protobuf message. No "
                    "protobuf message type specified to send."
                )
            response_data = self.send_type()

        copy_dict_to_pb(
            instance=response_data,
            dictionary=data
        )

        return Flask.response_class(
            response_data.SerializeToString(),
            mimetype=self.mimetype
        ), status_code, headers
Пример #4
0
def api():
    if request.method == 'OPTIONS':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'
        return resp
    if request.method == 'POST':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'
        data = request.json  # получаем данные

        # получаем или создаем нового пользователя
        user = get_or_create(db.session,
                             User,
                             ip_adress=str(request.remote_addr),
                             user_agent=str(parse(str(request.user_agent))))

        # вставляем запись истории с данным пользователем
        history = History(date=datetime.datetime.now(),
                          base=float(data[0]),
                          work_days=int(data[1]),
                          pay_days=int(data[2]),
                          coff=int(data[3]),
                          premium=float(data[4]),
                          result=str(data[5]))

        # сохраняем в БД
        user.histories.append(history)
        db.session.add(user)
        db.session.add(history)
        db.session.commit()
        return resp
    if request.method == 'GET':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'

        # запрос истории расчетов сортированный по дате
        query = db.session.query(History, User).join(User, History.user_id == User.id)\
            .order_by(History.date.desc()).all()

        # формируем данные для формата JSON
        records = []
        for history, user in query:
            records.append({
                'date': str(history.date),
                'ip': user.ip_adress,
                'user_agent': user.user_agent,
                'base': history.base,
                'work_days': history.work_days,
                'pay_days': history.pay_days,
                'coff': history.coff,
                'premium': history.premium,
                'result': history.result
            })

        # заносим данные в тело ответа
        resp.data = json.dumps(records)
        return resp
Пример #5
0
class NSSelection(Resource):

	def __init__(self):
		self.start_time = 0	
		self.elapsed_time = 0		
		self.info = "Class NSSelection implementing Nnssf_Selection running on process: "+str(os.getpid())
		print(self.info)
		self.path = "/NSSF/Nnssf_Selection/v2/api/NSSelection.py"
		self.app = Flask(__name__, static_folder='static')
	
	def get(self):
		self.start_time = time()
		request_args = parser.parse_args()
		print("[NSSF][INFO] --> path "+self.path)

		# Process the req_network_slice_information that comes from AMF
		if operator.eq(request_args['msg_type'],"req_network_slice_information"):
			rep_data = self.req_network_slice_information(request_args)
			response = self.app.response_class(response=json.dumps(rep_data),
                                  status=200,
                                  mimetype='application/json')			
			self.elapsed_time = time() - self.start_time
			print(f"{Fore.GREEN}--> ************************* [NSSF request] [req_network_slice_information] {Style.RESET_ALL}")	
			print(f"{Fore.GREEN}--> ************************* [NSSF request] [elapsed time]: "+ str(self.elapsed_time) +f"{Style.RESET_ALL}")	
			response_times.append(self.elapsed_time)
			#print("response times: ",response_times)	
			#print(len(response_times))		
			if len(response_times)==100:
				print(f"{Fore.RED}--> ************************* [NSSF request] [Average Response Time]: "+ str(sum(response_times)/100.0) +f"{Style.RESET_ALL}")	
		
			return response

		else:
			print("[NSSF][WARNING] --> No msg_type found "+request_args['msg_type'])
			rep_data = {"rep_data":"Msg type not found"}
			response = self.app.response_class(response=json.dumps(rep_data),
                                  status=200,
                                  mimetype='application/json')
			
			return response
	
		
	
	def req_network_slice_information(self, request_args):
		# It is assumed that there is the information of NSSAI
		if operator.eq(request_args['SST'],'4'):
			rep_data = {"rep_data":"AuthorizedNetworkSliceInfo"}
			return rep_data
		else:
			rep_data = {"rep_data":"NoAuthorizedNetworkSliceInfo"}
			return rep_data
Пример #6
0
 def get(self):
     # Add parameters
     parser = reqparse.RequestParser()
     parser.add_argument('group', type=str)
     # get parameters
     params = parser.parse_args()
     response_obj = {
         "symbol": ["AA", "BTCUSD", "SPX"],
         "description": ["Apple Inc", "Microsoft corp", "S&P 500 index"],
         "exchange-listed": "NYSE",
         "exchange-traded": "NYSE",
         "minmov": 1,
         "minmov2": 0,
         "pricescale": [1, 1, 100],
         "has-dwm": True,
         "has-intraday": True,
         "has-no-volume": [False, False, True],
         "type": ["stock", "stock", "index"],
         "ticker": ["AA", "BTCUSD", "SPX"],
         "timezone": "America/New_York",
         "session-regular": "0900-1600"
     }
     response_json = (json.dumps(response_obj, ensure_ascii=False))
     response = Flask.response_class(response=response_json)
     response.headers.add('Access-Control-Allow-Origin', '*')
     response.headers.add('Access-Control-Allow-Headers',
                          'Content-Type,Authorization')
     response.headers.add('Access-Control-Allow-Methods', 'GET')
     return response
Пример #7
0
 def get(self):
     # Add parameters
     parser = reqparse.RequestParser()
     parser.add_argument('symbol', type=str)
     parser.add_argument('from', type=int)
     parser.add_argument('to', type=int)
     parser.add_argument('resolution', type=str)
     # get parameters
     params = parser.parse_args()
     response_obj = {
         "s": "ok",
         "t": [1386493512, 1386493532, 1386493567, 1386493639],
         "c": [42.1, 43.4, 44.3, 42.8],
         "o": [41.0, 42.9, 43.7, 44.5],
         "h": [43.0, 44.1, 44.8, 44.5],
         "l": [40.4, 42.1, 42.8, 42.3],
         "v": [12000, 18500, 24000, 45000]
     }
     response_json = (json.dumps(response_obj, ensure_ascii=False))
     response = Flask.response_class(response=response_json)
     response.headers.add('Access-Control-Allow-Origin', '*')
     response.headers.add('Access-Control-Allow-Headers',
                          'Content-Type,Authorization')
     response.headers.add('Access-Control-Allow-Methods', 'GET')
     return response
Пример #8
0
    def get_senses(self, job_id, word):
        log.info('Job: {}: Grabbing senses for: \"{}\"'.format(job_id, word))

        senses = self._sense_vectors.get_senses(word, ignore_case=True)

        sense_dict = {}

        # For each sense_id, prob pair in senses
        for sense_id, prob in senses:
            # Put (sense_id, (prob, {most_similar_words})) into the dict
            sense_dict[sense_id] = {'probability': prob, 'most_similar': {}}

            # Get the related senses
            rsense_dict = {}
            # For each related sense, similarity score pair in the most similar senses
            # for the sense_id
            for rsense_id, sim in self._sense_vectors.wv.most_similar(
                    sense_id):
                # Put (related sense, similarity score) into the dict.
                rsense_dict[rsense_id] = sim

            # Add the completed related senses dict back to the overall dict.
            sense_dict[sense_id]['most_similar'] = rsense_dict

        # Flask has trouble using its dumps command and Python dicts, so make the response
        # manually. Fixable?
        response = Flask.response_class(response=json.dumps(sense_dict),
                                        status=200,
                                        mimetype='application/json')

        return response
Пример #9
0
def build_json_response(app: Flask,
                        content: Union[dict, list],
                        status: int = 200) -> Response:
    response = app.response_class(response=json.dumps(content),
                                  status=status,
                                  mimetype='application/json')
    return response
def create_app():
    app = Flask(__name__)
    app.config.from_object(settings)
    app.response_class = JSONResponse
    app.url_map.converters['list'] = ListConverter
    db.init_app(app)
    return app
Пример #11
0
 def get(self):
     # Add parameters
     parser = reqparse.RequestParser()
     parser.add_argument('symbol', type=str)
     # get parameters
     params = parser.parse_args()
     response_obj = {
         "symbol": "BTCUSD",
         "description": "Bitcoin USD Bitstamp",
         "exchange-listed": "Bitstamp",
         "exchange-traded": "Bitstamp",
         "minmov": 1,
         "minmov2": 0,
         "pricescale": 2,
         "has-dwm": True,
         "has-intraday": True,
         "has-no-volume": False,
         "type": "stock",
         "ticker": "BTCUSD",
         "timezone": "America/New_York",
         "session-regular": "24x7"
     }
     response_json = (json.dumps(response_obj, ensure_ascii=False))
     response = Flask.response_class(response=response_json)
     response.headers.add('Access-Control-Allow-Origin', '*')
     response.headers.add('Access-Control-Allow-Headers',
                          'Content-Type,Authorization')
     response.headers.add('Access-Control-Allow-Methods', 'GET')
     return response
Пример #12
0
def html5():  # $routeHandler
    # note: flask.Flask.response_class is set to `flask.Response` by default.
    # it can be overridden, but we don't try to handle that right now.
    resp = Flask.response_class(
        "<h1>hello</h1>"
    )  # $HttpResponse mimetype=text/html responseBody="<h1>hello</h1>"
    return resp  # $ SPURIOUS: HttpResponse mimetype=text/html responseBody=resp
Пример #13
0
def json_response(body, status_code=200, content_type="application/json"):
    """
    Encodes the provided body to JSON and returns a Flask JSON response object
    """
    return Flask.response_class(response=json.dumps(body),
                                status=status_code,
                                content_type=content_type)
Пример #14
0
def init_module():
    """ Initializes the Flask App. """

    app = Flask(__name__)
    app.response_class = CustomResponse
    database = PupDB(os.environ.get('PUPDB_FILE_PATH') or 'pupdb.json')
    return app, database
Пример #15
0
 def real_method(val, method=method, **kwargs):
     app = Flask('testing')
     app.response_class = FlaskRequestsResponse
     app.config['TESTING'] = True
     val.setup_webserver(app, **kwargs)
     app.add_url_rule('/__health', 'health', lambda: 'ok', methods=('GET',))
     return method(val, client=app.test_client(), **kwargs)
Пример #16
0
def create_app():
    """Set flask APP config, and start the data manager."""
    gunicorn_logger = setup_logger("gunicorn", "error")
    gunicorn_logger.info("create_app starts.")
    static_url_path = settings.URL_PATH_PREFIX + "/static"
    static_folder_path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'ui', 'dist', 'static'))

    app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder_path)
    app.config['JSON_SORT_KEYS'] = False

    if settings.ENABLE_CORS:
        CORS(app, supports_credentials=True)

    app.before_request(before_request)

    app.register_error_handler(HTTPException, error_handler.handle_http_exception_error)
    app.register_error_handler(MindInsightException, error_handler.handle_mindinsight_error)
    app.register_error_handler(Exception, error_handler.handle_unknown_error)

    app.response_class = CustomResponse

    _init_app_module(app)
    gunicorn_logger.info("create_app ends.")

    return app
Пример #17
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(config[object_name])
    app.response_class = MyResponse

    db.init_app(app)
    mail.init_app(app)

    rest_api = Api()
    rest_api.add_resource(CommentApi, '/api/comment',
                          '/api/comment/<int:comment_id>')
    rest_api.add_resource(AllCommentsApi, '/api/all_comments')
    rest_api.add_resource(RegisterApi, '/api/register')
    rest_api.add_resource(LoginApi, '/api/login')
    rest_api.add_resource(LogoutApi, '/api/logout')
    rest_api.add_resource(UserInfoApi, '/api/user_info',
                          '/api/user_info/<int:user_id>')
    rest_api.add_resource(AvatarApi, '/api/upload_avatar')
    rest_api.add_resource(BindEmailApi, '/api/bind_email')
    rest_api.add_resource(ConfirmEmailApi, '/api/confirm_email')
    rest_api.add_resource(ChangePasswordApi, '/api/change_password')
    rest_api.add_resource(SendVerifyEmailApi, '/api/send_verify_email')
    rest_api.add_resource(ForgetPasswordApi, '/api/forget_password')
    rest_api.add_resource(ReviseUserInfoApi, '/api/revise_user_info')
    rest_api.init_app(app)

    configure_uploads(app, photos)

    return app
Пример #18
0
def create_app():
    # initialize flask application
    app = Flask(__name__)

    # register all blueprints
    app.register_blueprint(foss_bp)
    app.register_blueprint(image_bp)

    # register custom response class
    app.response_class = response.JSONResponse

    # register before request middleware
    before_request_middleware(app=app)

    # register after request middleware
    after_request_middleware(app=app)

    # register after app context teardown middleware
    teardown_appcontext_middleware(app=app)

    # register custom error handler
    response.json_error_handler(app=app)

    # initialize the database
    init_db()

    return app
def handle_preflight():
    resp = Flask.response_class('')
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    resp.headers['Access-Control-Allow-Headers'] = 'User-Id, Patient-Id'
    resp.headers['Content-Type'] = 'text/html'
    return resp
Пример #20
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.users.models import db
    from app.color.models import db
    from app.size.models import db
    from app.product.models import db
    from app.category.models import db

    db.init_app(app)

    # Blueprints   
    from app.users.views import users
    from app.color.views import color
    from app.size.views import size
    from app.product.views import product
    from app.category.views import category

    app.register_blueprint(users, url_prefix='/api/v1/users')
    app.register_blueprint(color, url_prefix='/api/v1/color')
    app.register_blueprint(size, url_prefix='/api/v1/size')
    app.register_blueprint(product, url_prefix='/api/v1/product')
    app.register_blueprint(category, url_prefix='/api/v1/category')
    

    return app
    
Пример #21
0
def create_app(config_name):
    app = Flask(__name__)
    app.response_class = MyResponse
    swagger.init_app(app)
    app.config['BOOTSTRAP_SERVE_LOCAL'] = True
    bootstrap.init_app(app)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    dropzone.init_app(app)

    # login_manager.init_app(app)
    db.init_app(app)
    bcrypt.init_app(app)

    handler = logging.FileHandler(filename="server.log", encoding='utf-8')
    handler.setLevel("DEBUG")
    format_ = "%(asctime)s[%(name)s][%(levelname)s] :%(levelno)s: %(message)s"
    formatter = logging.Formatter(format_)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint, url_prefix='/')

    return app
Пример #22
0
def create_app():
    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'sahyog-secret'
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=10)
    app.config.update(dict(
        NAMEKO_AMQP_URI='amqp://localhost:5672'
    ))
    app.config['MONGODB_URI_KEY'] = 'mongodb://localhost:27017/Sahyog'

    app.config["LOG_TYPE"] = os.environ.get("LOG_TYPE", "stream")
    app.config["LOG_LEVEL"] = os.environ.get("LOG_LEVEL", "INFO")

    logs = LogSetup()
    logs.init_app(app)

    rpc.init_app(app)
    login_manager = LoginManager()
    login_manager.login_view = 'main.index'
    login_manager.init_app(app)

#    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
       user =  rpc.user_service.getUserById(user_id)
       print(type(user))
       userLoaded = User(user_dict=user)
       print(userLoaded.user_dict)
       return userLoaded

    # Did I mention we log timestamps in UTC here?
    @app.after_request
    def after_request(response):
        """ Logging after every request. """
        logger = logging.getLogger("app.access")
        logger.info(
        "%s [%s] %s %s %s %s %s %s",
            request.remote_addr,
            dt.utcnow().strftime("%d/%b/%Y:%H:%M:%S.%f")[:-3],
            request.method,
            request.path,
            request.json,
            response.status,
            request.referrer,
            request.user_agent,
        )
        return response


    app.response_class = ApiResponse
    # blueprint for auth routes in our app
    from .resources.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .resources.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
Пример #23
0
def client_with_response_class():
    test_app = Flask("test")
    test_app.config["TESTING"] = True
    test_app.response_class = LowballResponse

    with test_app.test_request_context() as client:
        yield client
Пример #24
0
class server():
    def __init__(self):
        print("Start server")

        self.printers = []
        self.printer_class = {}

        self.db = pymongo.MongoClient('localhost', 27017)['OFarm']

        self.pf = PrinterFarm(self.db)
        #self.pf.start()
        self.api = Api(self.db, self.pf)
        self.app = Flask('OFarm', template_folder='O3Farm/templates')
        self.start()

        self.app.config['TEMPLATES_AUTO_RELOAD'] = True
        self.app.config['TESTING'] = True
        self.app.config['DEBUG'] = True
        self.app.config['ENV'] = "development"
        self.app.run(host="0.0.0.0", port=9006)



    def start(self):

        self.pf.load_printers()
        #self.load_printers()
        
        self.queue = Queue(connection=Redis())
        self.scheduler = Scheduler(connection=Redis())

        self.app.add_url_rule('/', 'index', self.index)
        self.app.add_url_rule('/printers', 'printers', self.get_printers)
        self.app.add_url_rule('/printer/<id>/', 'printer', self.printer)

        self.api.add_rules(self.app)
        self.pf.add_rules(self.app)


    def index(self):
        print(request)
        print(request.json)
        print(request.data)
        #result = self.queue.enqueue(long)
        return render_template('index.html', title='Home')


    def get_printers(self, status = True):
        response = self.app.response_class(
            response=bson.json_util.dumps(self.pf.get_printers(update = True)),
            status=200,
            mimetype='application/json'
        )
        return response

    def printer(self, id):
        id = bson.ObjectId(id)
        p = self.pf.get_printer(id, update = True)
        print(p['name'])
        return(bson.json_util.dumps(p))
Пример #25
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.response_class = MyResponse
    app.config.from_object(config_class)
    app.logger = logging.getLogger("werkzeug")

    CORS(app=app, origins="*", methods=['GET', 'POST'])

    #import statements for blueprints
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    from app.resume_parser import bp as resume_parser_bp
    app.register_blueprint(resume_parser_bp)

    if not app.debug:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/resume_parser.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("Resume Parser startup")

    return app
Пример #26
0
def search_members():
    request_data = request.get_json()
    print(request_data)
    respond_data = request_data
    filtered_member = []
    for memebr in members:
        name = ' '.join([memebr['firstName'], memebr['lastName']])
        match_name = re.search(r"{}".format(request_data['name']),
                               name) if request_data['name'] != '' else True
        match_dob = re.search(
            r"{}".format(request_data['dob']),
            memebr['dob']) if request_data['dob'] != '' else True
        match_city = re.search(
            r"{}".format(request_data['city']),
            memebr['address']) if request_data['city'] != '' else True
        match_county = re.search(
            r"{}".format(request_data['county']),
            memebr['address']) if request_data['county'] != '' else True
        # match_city = re.search(r"{}".format(request_data['city']), memebr['address']) if request_data['city'] != '' else True
        # print (match1)
        if match_name and match_dob and match_city and match_county:
            filtered_member.append(memebr)
            print(memebr)
    respond_data.update({
        "count":
        len(filtered_member),
        "members":
        filtered_member[request_data['offset']:request_data['offset'] +
                        request_data['limit']]
    })

    response = Flask.response_class(response=json.dumps(respond_data),
                                    status=200,
                                    mimetype='application/json')
    return response
Пример #27
0
def disconnect():
    """Closes the ZeroDB connection."""
    if 'username' in session:
        username = session.pop('username')
        if username in dbs:
            del dbs[username]
    return Flask.response_class(status=204)
Пример #28
0
def get_Receipt_Category():
    #CODE TO CLASSIFY RECEIPT CATEGORY
    value = request.get_json()
    data = value['RawText']
    clf = pickle.load(open('test_finalized_Receipt_model1.sav', 'rb'))
    count_vect = pickle.load(open('test_countvector1.sav', 'rb'))
    test = count_vect.transform([data])
    result = clf.predict(test)
    category = result[0]

    #CODE TO CLASSIFY MERCHANT CATEGORY
    clf = pickle.load(open('finalized_vendor_model.sav', 'rb'))
    count_vect = pickle.load(open('vendor_countvector.sav', 'rb'))
    m_test = count_vect.transform([data])
    m_result = clf.predict(m_test)
    merchant = m_result[0]

    #CODE FOR EXTRACT DATE
    receiptDate = get_Receipt_Date(data)

    #CODE FOR MAX TOTAL AMOUNT
    numbers = re.findall('\d*\.\d+', data)
    numbers = map(float, numbers)
    totalAmount1 = str(max(numbers))
    totalAmount2 = get_Total_Amount(data)
    #print('totalAmount'+totalAmount)
    return Flask.response_class(json.dumps({
        'receiptCategory': category,
        'maxTotalAmount1': totalAmount1,
        'totalAmount2': totalAmount2,
        'receiptDate': receiptDate,
        'merchant': merchant
    }),
                                mimetype=u'application/json')
Пример #29
0
def create_app(config_name=None):
    if config_name is None:
        # config_name = os.getenv('FLASK_CONFIG', 'development')
        config_name = os.getenv('FLASK_CONFIG', 'production')

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.response_class = XMLResponse

    # Add analytics
    from flask_analytics import Analytics
    from rsshub.google_analytics import ga_account

    Analytics(app)
    app.config['ANALYTICS']['GOOGLE_UNIVERSAL_ANALYTICS'][
        'ACCOUNT'] = ga_account
    app.config['ANALYTICS']['ENABLED'] = True

    register_blueprints(app)
    register_extensions(app)
    register_errors(app)
    register_context_processors(app)
    register_cli(app)

    return app
Пример #30
0
def create_app(config_name=None, register_routes=True, register_cli=True):
    app = Flask(__name__)

    # Config
    config_name = config_name or (os.getenv('FLASK_CONFIG') or 'development')
    app.config.from_object(config[config_name])
    app.config.from_object(
        config_confidential)  # override confidential configuration values
    if config_name == 'testing':
        app.config['SQLALCHEMY_DATABASE_URI'] = app.config[
            'SQLALCHEMY_TESTING_DATABASE_URI']

    # Response
    class AppResponse(Response):
        default_mimetype = 'text/html'

    app.response_class = AppResponse

    # Allow Cors
    CORS(app, supports_credentials=True)

    # Initialize database
    db.init_app(app)
    Migrate(app, db, compare_type=True)

    # jwt
    JWTManager(app)

    # Register routes
    if register_routes:
        rest_api.init_app(app)

    # Register CLI
    if register_cli:
        from manage_api.cli.tune_db import cli as tune_cli

        app.cli.add_command(tune_cli)

    # Handlers

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.errorhandler(NotImplementedError)
    def handle_not_implemented(error):
        response = 'NOT IMPLEMENTED'
        response.status_code = 501
        return response

    @app.before_request
    def for_cors():
        if request.method == 'OPTIONS':
            return jsonify({})

    return app
Пример #31
0
def app():
    app = Flask(__name__)

    class TestResponse(app.response_class, JSONResponseMixin):
        pass

    app.response_class = TestResponse
    app.test_client_class = ApiClient
    return app
Пример #32
0
def create_app(config_filename):
    app = Flask(__name__, template_folder='../templates')
    app.response_class = MyResponse

    app.debug = True
    app.register_error_handler(404, page_not_found)

    bootstrap = Bootstrap(app)
    return bootstrap
Пример #33
0
def memebr_list_report():
    request_data = request.get_json()
    ico_ccaids = request_data['ico']
    sco_ccaids = request_data['sco']
    ico_query = "','".join(ico_ccaids) if len(ico_ccaids) > 0 else None
    sco_query = "','".join(sco_ccaids) if len(sco_ccaids) > 0 else None

    ico_query = """select nn.NAME_ID as NAME_ID, nn.TEXT2 as CCA_ID, nn.NAME_FIRST as NAME_FIRST, nn.NAME_LAST as NAME_LAST,nn.BIRTH_DATE as BIRTH_DATE, nn.SOC_SEC as SSN,
                    ms.product as PRODUCT, ms.START_DATE as P_START_DATE, ms.END_DATE as P_END_DATE, ms.ENR_STAT,
                    rc.rc as RC, rc.RCStart as RCStart, rc.RCEnd as RCEnd,
                    na.ADDRESS1, na.ADDRESS2, na.ADDRESS3, na.CITY, na.STATE, na.ZIP, na.COUNTRY, na.COUNTY, na.START_DATE, na.END_DATE
                    from MPSnapshotProd.dbo.NAME as nn
                    left join MPSnapshotProd.dbo.NAME_ADDRESS as na on na.NAME_ID = nn.NAME_ID and na.ADDRESS_TYPE = 'PERMANENT' and GETDATE() >= na.START_DATE and (GETDATE() <= na.START_DATE or na.END_DATE is null)
                    left join ReportSupport.dbo.Member_Spans as ms on ms.NAME_ID = nn.NAME_ID and GETDATE() >= ms.START_DATE and (GETDATE() <= ms.END_DATE or ms.END_DATE is null)
                   	left join ReportSupport.dbo.vwICORatingCategories_MdsAssist as rc on rc.MPMemberId = nn.NAME_ID and GETDATE() >= rc.RCStart and (GETDATE() <= rc.RCEnd or rc.RCEnd is null) 
                   	where nn.TEXT2 in ('{}')""".format(
        ico_query) if ico_query else ''

    sco_query = """ select nn.NAME_ID as NAME_ID, nn.TEXT2 as CCA_ID, nn.NAME_FIRST as NAME_FIRST, nn.NAME_LAST as NAME_LAST,nn.BIRTH_DATE as BIRTH_DATE, nn.SOC_SEC as SSN,
                    ms.product as PRODUCT, ms.START_DATE as P_START_DATE, ms.END_DATE as P_END_DATE, ms.ENR_STAT,
                    rc.rc as RC, rc.RCStart as RCStart, rc.RCEnd as RCEnd,
                    na.ADDRESS1, na.ADDRESS2, na.ADDRESS3, na.CITY, na.STATE, na.ZIP, na.COUNTRY, na.COUNTY, na.START_DATE, na.END_DATE
                    from MPSnapshotProd.dbo.NAME as nn
                    left join MPSnapshotProd.dbo.NAME_ADDRESS as na on na.NAME_ID = nn.NAME_ID and na.ADDRESS_TYPE = 'PERMANENT' and GETDATE() >= na.START_DATE and (GETDATE() <= na.START_DATE or na.END_DATE is null)
                    left join ReportSupport.dbo.Member_Spans as ms on ms.NAME_ID = nn.NAME_ID and GETDATE() >= ms.START_DATE and (GETDATE() <= ms.END_DATE or ms.END_DATE is null)
                   	left join ReportSupport.dbo.vwICORatingCategories_MdsAssist as rc on rc.MPMemberId = nn.NAME_ID and GETDATE() >= rc.RCStart and (GETDATE() <= rc.RCEnd or rc.RCEnd is null) 
                   	where nn.TEXT2 in ('{}')""".format(
        sco_query) if sco_query else ''

    cursor = cnxn.cursor()
    query_list = ico_query + sco_query

    result = cursor.execute(query_list)
    members = jsonify_members(result)

    if ico_query and sco_query:
        result.nextset()
        members = members + jsonify_members(result)

    print(' query_list ######################################################')
    print(query_list)
    print(' query_list ######################################################')
    print("    ")
    print("    ")
    print(' members ######################################################')
    print(members)
    print(' members ######################################################')
    respond_data = {'members': members}
    # respond_data = {'members': [row for row in result.fetchall()]}
    # result.nextset()
    # respond_data['members'].append(list(row for row in result.fetchall()))
    cursor.close()
    response = Flask.response_class(response=json.dumps(respond_data),
                                    status=200,
                                    mimetype='application/json')
    return response
Пример #34
0
        def to_response(*args, **kwargs):

            request.data_dict = self.parse_request_data(request)
            try:
                result = fn(*args, **kwargs)
            except JsonDictKeyError:
                abort(400)

            # Similar to flask's app.route, returned werkzeug responses are
            # passed directly back to the caller
            if isinstance(result, Response):
                return result

            # If the view method returns a default flask-style tuple throw
            # an error as when making rest API's the view method more likely
            # to return dicts and status codes than strings and headres
            if (isinstance(result, tuple) and (
                len(result) == 0 or
                not isinstance(result[0], dict)
            )):
                raise EncodeError(
                    "Pbj does not support flask's default tuple format "
                    "of (response, headers) or (response, headers, "
                    "status_code). Either return an instance of "
                    "flask.response_class to override pbj's response "
                    "encoding or return a tuple of (dict, status_code) "
                    "or (dict, status_code, headers)."
                )

            # Verify the server can respond to the client using
            # a mimetype the client accepts. We check after calling because
            # of the nature of Http 406
            mimetype = self.response_mimetype(request)
            if not mimetype:
                abort(406)  # Not Acceptable

            # If result is just an int, it must be a status code, so return
            # the response with no data and a status code
            if isinstance(result, int):
                return Flask.response_class("", mimetype=mimetype), result, []

            data, status_code, headers = _result_to_response_tuple(result)

            if not isinstance(data, dict):
                raise EncodeError(
                    "Methods decorated with api must return a dict, int "
                    "status code or flask Response."
                )

            return self.codecs[mimetype].make_response(
                data,
                status_code,
                headers
            )
Пример #35
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    app.response_class = ApiResponse

    return app
Пример #36
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    db.init_app(app)

    # Blueprints
    from app.auth.views import auth
    app.register_blueprint(auth, url_prefix='/api/v1/auth')

    return app
Пример #37
0
def delete(model_name, oid):
    """Deletes an object based on its model name and objectID."""
    db = session_db_or_403()
    model = model_or_404(model_name)

    try:
        with transaction.manager:
            db[model].remove(oid)
    except KeyError:
        abort(404)

    return Flask.response_class(status=204)
Пример #38
0
def create_app(config=None, app_name=None):

    if app_name is None:
        app_name = DEFAULT_APPNAME

    app = Flask(app_name, static_folder=None)
    app.response_class = JSONTypeResponse

    configure_app(app, config)
    configure_db(app)
    configure_api(app)

    return app
Пример #39
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.users.models import db
    db.init_app(app)

    # Blueprints
    from app.users.views import users
    app.register_blueprint(users, url_prefix='/api/v1/users')

    return app
Пример #40
0
Файл: pb.py Проект: GermainZ/pb
def create_app(config_filename='config.yaml'):
    app = Flask(__name__)
    app.response_class = TextResponse
    app.url_map.converters['id'] = IDConverter
    app.url_map.converters['sha1'] = SHA1Converter

    load_yaml(app, config_filename)
    init_db(app)
    init_cache(app)

    app.register_blueprint(paste)
    app.register_blueprint(url)

    return app
Пример #41
0
def create_app(configuration):
    app = Flask(__name__)
    app.config.from_object(configuration)
    app.response_class = MyResponse

    db.init_app(app)

    # Blueprints
    from app.resources.resources import bucket_list
    app.register_blueprint(bucket_list, url_prefix='/api/v1')

    # Gzip response
    compress.init_app(app)
    return app
Пример #42
0
def connect():
    """Opens a ZeroDB connection.

    A JSON object containing a valid 'username' and 'passphrase' should be
    sent as the request body. Additionally, a 'host' and optional 'port' can
    be supplied to specify the ZeroDB server location; otherwise defaults will
    be used.

    The response will contain an authorization cookie that should be used
    in future requests.
    """
    data = request.get_json()
    username = data.get('username')
    passphrase = data.get('passphrase')

    if zeo_socket:
        socket = zeo_socket
    else:
        host = data.get('host')
        port = data.get('port')
        if host and port:
            socket = (host, port)
        elif host:
            socket = host
        else:
            socket = None

    if not (username and passphrase and socket):
        resp = jsonify(error="Incomplete login information.")
        resp.status_code = 400
        return resp

    try:
        db = zerodb.DB(socket, username=username, password=passphrase)
    except Exception as ex:
        resp = jsonify(error=str(ex),
                       error_class=ex.__class__.__name__)
        resp.status_code = 400
        return resp

    session['username'] = username
    dbs[username] = db

    return Flask.response_class(status=204)
Пример #43
0
def app(view_and_schema):
    view_class, schema, _ = view_and_schema
    blueprint = FlumpBlueprint('flump', __name__)
    blueprint.register_flump_view(view_class, '/user/')

    app = Flask(__name__)
    app.response_class = FlumpTestResponse
    app.config['SERVER_NAME'] = 'localhost'
    app.config['SERVER_PROTOCOL'] = 'http'
    app.config['DEBUG'] = True
    app.config['TESTING'] = True

    app.register_blueprint(blueprint, url_prefix='/tester')

    ctx = app.app_context()
    ctx.push()
    try:
        yield app
    finally:
        ctx.pop()
Пример #44
0
def get_application():
    application = Flask('rtmpt')
    application.config.update({
        'SECRET_KEY': 'secret_key',
        'RMPT_INTERVALS': (b'\x01', b'\x03', b'\x05', b'\x09', b'\x11', b'\x21'),
        'RTMP_FAIL_RAMPUP': 10,
        'RTMP_SERVER': ('127.0.0.1', 1935),
        'RTMPT_DEFAULT_CONTENT_TYPE': 'application/x-fcs',
        'RTMP_BUFFER_SIZE': 8 * 1024,
        'RTMP_TIMEOUT': 0.020,
    })
    # application.config.from_object(
        # os.environ.get('SETTINGS_MODULE', 'rtmpt.settings').strip())

    application.response_class = RTMPTResponse

    # Installed Apps
    from .views import application as bp
    application.register_blueprint(bp, url_prefix='')
    
    return application
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.models import db
    db.init_app(app)

    # Blueprints   
    from app.users.views import users
    app.register_blueprint(users, url_prefix='/api/v1/users')
    
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    return app
    
 def test_save_session(self):
     sessint = self.session_interface
     sid = sessint.generate_sid()
     key = self.prefix + sid
     val = pickle.dumps(dict(a='a1', b='b1'))
     ten_seconds = 10
     self.redis.setex(key, ten_seconds, val)
     with self.app.test_request_context('/'):
         current_request = request._get_current_object()
         cookie_name = self.app.session_cookie_name
         current_request.cookies = {cookie_name: sid}
         sess = sessint.open_session(self.app, current_request)
         newval = 'b1-modified'
         sess['b'] = newval
         resp = Flask.response_class()
         resp = self.app.process_response(resp)
         sessint.save_session(self.app, sess, resp)
         val = self.redis.get(key)
         val = pickle.loads(val)
         cookie = resp.headers.get('Set-Cookie')
         self.assertEqual(newval, val['b'])
         self.assertIn('session='+sid, cookie)
 def test_delete_session(self):
     sessint = self.session_interface
     sid = sessint.generate_sid()
     key = self.prefix + sid
     val = pickle.dumps(dict(a='a1', b='b1'))
     ten_seconds = 10
     self.redis.setex(key, ten_seconds, val)
     with self.app.test_request_context('/'):
         current_request = request._get_current_object()
         cookie_name = self.app.session_cookie_name
         current_request.cookies = {cookie_name: sid}
         sess = sessint.open_session(self.app, current_request)
         sess.clear()
         resp = Flask.response_class()
         resp = self.app.process_response(resp)
         val1 = self.redis.get(key)
         sessint.save_session(self.app, sess, resp)
         val2 = self.redis.get(key)
         cookie = resp.headers.get('Set-Cookie')
         self.assertIsNotNone(val1)
         self.assertIsNone(val2)
         self.assertIn('session=;', cookie)
Пример #48
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    #Init Flask-SQLAlchemy
    from app.basemodels import db
    db.init_app(app)

    # Blueprints
    from app.followers.views import followers
    app.register_blueprint(followers, url_prefix='/followers')

    from app.statistics.views import statistics
    app.register_blueprint(statistics, url_prefix='/statistics')

    from app.tweets.views import tweets
    app.register_blueprint(tweets, url_prefix='/tweets')

    from app.users.views import users
    app.register_blueprint(users, url_prefix='/users')

    return app
Пример #49
0
def create_app():
    app = Flask(__name__, static_folder='../public/', static_url_path='/public')
    app.response_class = ResponseJSON
    app.config.from_pyfile(config.FLASK_CONFIG_PATH)

    # change debug output formatter to a pretty one-liner
    format = Formatter("%(levelname)6s | %(relativeCreated)6d | %(filename)s:%(lineno)d | %(message)s")
    app.logger.handlers[0].setFormatter(format)

    # resolve paths relative to this file
    app_path = path.dirname(__file__)
    app.config.update({
        'RECORDINGS_PATH': path.realpath(app_path + '/../public/recordings/'),
        'PATH_USER_PROFILE_IMAGE': path.realpath(app_path + '/../public/profile_images/'),
        'PATH_ASSETS': path.realpath(app_path + '/../public/assets/'),
        'PATH_PUBLIC': path.realpath(app_path + '/../public/'),
    })

    # sanity checks
    if not path.isdir(app.config['RECORDINGS_PATH']):
        raise Exception("Recordings path does not exist: " + app.config['RECORDINGS_PATH'])

    if not path.isdir(app.config['PATH_USER_PROFILE_IMAGE']):
        raise Exception("User profile images path does not exist: " + app.config['PATH_USER_PROFILE_IMAGE'])

    # app.json_encoder = MongoJsonEncoder

    # setup database and session storage
    # db settings come from flask.ini
    # and same engine is used for storing sessions
    mongo = MongoEngine()
    mongo.init_app(app)
    app.session_interface = MongoEngineSessionInterface(mongo)

    # toolbar = DebugToolbarExtension(app)

    return app, mongo
Пример #50
0
from urllib import urlencode
import os

from flask import Flask, redirect, request
import requests

from pylexa.app import alexa_blueprint, handle_launch_request
from pylexa.intent import handle_intent
from pylexa.response import (
    AlexaResponseWrapper, LinkAccountCard, PlainTextSpeech, Response, SimpleCard
)


app = Flask(__name__)
app.register_blueprint(alexa_blueprint)
app.response_class = AlexaResponseWrapper

AWS_VENDOR_ID = os.getenv('AWS_VENDOR_ID')
SLACK_CLIENT_ID = os.getenv('SLACK_CLIENT_ID')
SLACK_CLIENT_SECRET = os.getenv('SLACK_CLIENT_SECRET')
SLACK_CHANNEL = os.getenv('SLACK_CHANNEL', 'botstuff')


@app.before_request
def log_request_json():
    print request.headers
    print request.json


@handle_launch_request
def handle_launch(request):
Пример #51
0
        success = True

    return app.response_class(json.dumps({'login_result': success}), content_type='application/json')


@app.route('/nest/devices', methods=['GET'])
def list_devices():

    try:
        nest.check_login()
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    devices = map(lambda device: device.name, nest.list_devices())
    return app.response_class(json.dumps({'devices': devices}), content_type='application/json')


@app.route('/device/<deviceid>/<property>/<value>', methods=['PUT'])
def set_value(deviceid, property, value):

    _log.info('{0} {1} {2}'.format(deviceid, property, value))
    success = False
    try:
        nest.check_login()
        success = nest.set_property(deviceid, property, value)

    except LogInException, ex:
        _log.error(ex.message)
        abort(401, ex.message)
    except (NotFoundException, AttributeError), ex:
from flask import Flask, jsonify
from werkzeug.wrappers import Response
from werkzeug.wsgi import DispatcherMiddleware

app = Flask(__name__)
json_page = Flask(__name__)


class JSONResponse(Response):
    @classmethod
    def force_type(cls, rv, environ=None):
        if isinstance(rv, dict):
            rv = jsonify(rv)
        return super(JSONResponse, cls).force_type(rv, environ)

json_page.response_class = JSONResponse


@json_page.route('/hello/')
def hello():
    return {'message': 'Hello World!'}


@app.route('/')
def index():
    return 'The index page'


app.wsgi_app = DispatcherMiddleware(app.wsgi_app, OrderedDict((
    ('/json', json_page),
)))
Пример #53
0
# -*- coding: utf-8 -*-
from .responses import JSONResponse, connection_error, authenticate
from .utils import encode_auth
from .crawler import Crawler
from .exceptions import AuthError
from urllib3.exceptions import MaxRetryError
from flask import Flask, request, jsonify, make_response
from functools import wraps


app = Flask(__name__)
app.response_class = JSONResponse


@app.errorhandler(404)
def not_found(e=None):
    """Return a JSON with error on 404, instead of ugly HTML"""
    return make_response(jsonify({"errore": u"Una o più risorse non trovate."}), 404)


def requires_auth(f):
    """Decorator for authentication"""

    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if (not auth) or (not auth.username) or (not auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated
Пример #54
0
from flask import Flask, Response
from ricecrew import settings

class XhtmlResponse(Response):
    default_mimetype = 'application/xhtml+xml'

app = Flask(__name__)
app.config.from_object(settings)
app.response_class = XhtmlResponse
Пример #55
0
import models

class MyResponse(Response):
    def __init__(self, response=None, **kwargs):
        kwargs['headers'] = ''
        headers = kwargs.get('headers')
        # 跨域控制
        origin = ('Access-Control-Allow-Origin', '*')
        if headers:
            headers.add(*origin)
        else:
            headers = Headers([origin])
        kwargs['headers'] = headers
        return super().__init__(response, **kwargs)

app.response_class = MyResponse

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

@app.route('/cities')
def cities():
    obj_list = models.City.query.all()
    return render_template('list.html',title='城市', obj_list=obj_list)

@app.route('/city_add', methods=['POST'])
def city_add():
    print('Call city_add....')
    city_name = request.form['obj_name']
    print(city_name)
Пример #56
0
def app(request):
    app = Flask(__name__)
    app.response_class = Response
    app.debug = True
    app.config['SECRET_KEY'] = 'secret'
    app.config['TESTING'] = True
    app.config['LOGIN_DISABLED'] = False
    app.config['WTF_CSRF_ENABLED'] = False

    for opt in ['changeable', 'recoverable', 'registerable',
                'trackable', 'passwordless', 'confirmable']:
        app.config['SECURITY_' + opt.upper()] = opt in request.keywords

    if 'settings' in request.keywords:
        for key, value in request.keywords['settings'].kwargs.items():
            app.config['SECURITY_' + key.upper()] = value

    mail = Mail(app)
    app.mail = mail

    @app.route('/')
    def index():
        return render_template('index.html', content='Home Page')

    @app.route('/profile')
    @login_required
    def profile():
        return render_template('index.html', content='Profile Page')

    @app.route('/post_login')
    @login_required
    def post_login():
        return render_template('index.html', content='Post Login')

    @app.route('/http')
    @http_auth_required
    def http():
        return 'HTTP Authentication'

    @app.route('/http_custom_realm')
    @http_auth_required('My Realm')
    def http_custom_realm():
        return render_template('index.html', content='HTTP Authentication')

    @app.route('/token', methods=['GET', 'POST'])
    @auth_token_required
    def token():
        return render_template('index.html', content='Token Authentication')

    @app.route('/multi_auth')
    @auth_required('session', 'token', 'basic')
    def multi_auth():
        return render_template('index.html', content='Session, Token, Basic auth')

    @app.route('/post_logout')
    def post_logout():
        return render_template('index.html', content='Post Logout')

    @app.route('/post_register')
    def post_register():
        return render_template('index.html', content='Post Register')

    @app.route('/admin')
    @roles_required('admin')
    def admin():
        return render_template('index.html', content='Admin Page')

    @app.route('/admin_and_editor')
    @roles_required('admin', 'editor')
    def admin_and_editor():
        return render_template('index.html', content='Admin and Editor Page')

    @app.route('/admin_or_editor')
    @roles_accepted('admin', 'editor')
    def admin_or_editor():
        return render_template('index.html', content='Admin or Editor Page')

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

    @app.route('/page1')
    def page_1():
        return 'Page 1'
    return app
Пример #57
0
from Manager.ProxyManager import ProxyManager

app = Flask(__name__)


class JsonResponse(Response):

    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (dict, list)):
            response = jsonify(response)

        return super(JsonResponse, cls).force_type(response, environ)


app.response_class = JsonResponse

api_list = {
    'get': u'get an usable proxy',
    # 'refresh': u'refresh proxy pool',
    'get_all': u'get all proxy from proxy pool',
    'delete?proxy=127.0.0.1:8080': u'delete an unable proxy',
    'get_status': u'proxy statistics'
}


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

Пример #58
0
app = Flask(__name__)
_log = get_logger(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
nest = NestIntegration()


@app.route('/homekit/devices', methods=['GET'])
def list_devices():
    try:
        res = requests.get("{0}/{1}".format(HOMEKIT_URL,"devices"))
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    toret = res.json() if res.content != '' else {"error": "error"}
    return app.response_class(json.dumps(toret), content_type='application/json')

@app.route('/homekit/<room_name>/devices', methods=['GET'])
def list_room_devices(room_name):

    try:
        res = requests.get("{0}/{1}/{2}".format(HOMEKIT_URL,"room", room_name))
        print res.json()
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    toret = res.json() if res.content != '' else {"error": "error"}
    return app.response_class(json.dumps(toret), content_type='application/json')

@app.route('/homekit/property/<room>/<accessory>/<service>/<property>', methods=['POST'])
Пример #59
0
def make_app():
    cors = CORS(origins=[
        'https://app.communityshare.us:443', # production app
        'http://communityshare.localhost:5000', # local dev angular app
        'http://communityshare.localhost:8000', # local dev elm app
        'https://dmsnell.github.io/cs-elm/', # live elm app
    ])
    compress = Compress()
    webpack = Webpack()
    app = Flask(__name__, template_folder='../static/')
    app.response_class = JsonifyDictResponse

    app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_CONNECTION
    app.config['WEBPACK_ASSETS_URL'] = config.WEBPACK_ASSETS_URL
    app.config['WEBPACK_MANIFEST_PATH'] = config.WEBPACK_MANIFEST_PATH

    cors.init_app(app)
    compress.init_app(app)
    webpack.init_app(app)

    if config.SSL != 'NO_SSL':
        flask_sslify.SSLify(app)
        app.wsgi_app = ReverseProxied(app.wsgi_app)

    register_user_routes(app)
    register_search_routes(app)
    register_conversation_routes(app)
    register_share_routes(app)
    register_survey_routes(app)
    register_email_routes(app)
    register_statistics_routes(app)

    community_share.api.register_routes(app)

    @app.teardown_appcontext
    def close_db_connection(exception):
        store.session.remove()

    @app.errorhandler(BadRequest)
    def handle_bad_request(error):
        return str(error), HTTPStatus.BAD_REQUEST

    app.errorhandler(Unauthorized)(jsonify_with_code(HTTPStatus.UNAUTHORIZED))
    app.errorhandler(Forbidden)(jsonify_with_code(HTTPStatus.FORBIDDEN))
    app.errorhandler(NotFound)(jsonify_with_code(HTTPStatus.NOT_FOUND))
    app.errorhandler(InternalServerError)(jsonify_with_code(HTTPStatus.INTERNAL_SERVER_ERROR))

    @app.route('/static/build/<path:filename>')
    def build_static(filename):
        return send_from_directory(
            app.root_path + '/../static/build/',
            filename,
            cache_timeout=YEAR_IN_SECONDS,
        )

    @app.route('/static/js/<path:filename>')
    def js_static(filename):
        return send_from_directory(app.root_path + '/../static/js/', filename)

    @app.route('/static/fonts/<path:filename>')
    def fonts_static(filename):
        return send_from_directory(app.root_path + '/../static/fonts/', filename)

    @app.route('/static/css/<path:filename>')
    def css_static(filename):
        return send_from_directory(app.root_path + '/../static/css/', filename)

    @app.route('/static/templates/footer.html')
    def footer_template():
        return render_template('templates/footer.html', config=config)

    @app.route('/static/templates/<path:filename>')
    def templates_static(filename):
        return send_from_directory(app.root_path + '/../static/templates/', filename)

    @app.route('/')
    def index():
        logger.debug('rendering index')
        return render_template('index.html', config=config)

    return app
Пример #60
0
app = Flask(__name__)

#config object, load oduction from envvar
app.config.from_object(config)

db = redis.StrictRedis(db=0)

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)

# 32 mb max upload size
patch_request_class(app, 32 * 1024 * 1024)

#boiler plate json response
RESP_DICT = {'data': [], 'status': 404}
resp = app.response_class(mimetype='application/json')


def return404():
    #this does not overwrite global vars
    RESP_DICT = {'data': [], 'status': 404}
    resp.data = json.dumps(RESP_DICT)
    resp.status_code = 404
    return resp


def return400():
    #this does not overwrite global vars
    RESP_DICT['status'] = 400
    RESP_DICT['data'] = ['Invalid request!']
    resp.data = json.dumps(RESP_DICT)