示例#1
0
def test_addresses_get_success(url, client):
    uid = json.loads(login(client).data)['uid']
    resp = client.get(url, content_type='application/json')

    assert json.loads(resp.data) == {}
    assert resp.status_code == 200
    logout(client, uid)
示例#2
0
def test_addresses_put_201(url, client):
    uid = json.loads(login(client).data)['uid']
    resp = client.put(url, data=json.dumps(first_address),
                      content_type='application/json')

    response_data = json.loads(resp.data)
    assert 'id' in response_data
    assert response_data['city'] == first_address['city']
    assert resp.status_code == 201
    logout(client, uid)
示例#3
0
def test_address_creation_failed_no_data(url, client):
    data = first_address.copy()
    del data['type'], data['city'], data['street']
    uid = json.loads(login(client).data)['uid']
    resp = client.post(url, data=json.dumps(data),
                       content_type='application/json')

    assert 'type' in json.loads(resp.data)
    assert 'city' in json.loads(resp.data)
    assert 'street' in json.loads(resp.data)
    assert resp.status_code == 400

    logout(client, uid)
示例#4
0
def sql_select():
    statement = request.args['sql']
    params = request.args['params']
    bind = request.args.get('bind')
    bind = bind if bind != '' else None

    # Validate hash
    hash = hashlib.sha1(current_app.config['SECRET_KEY'] + statement +
                        params).hexdigest()
    if hash != request.args['hash']:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith('select'):
        return abort(406)

    params = json.loads(params)

    engine = SQLAlchemy().get_engine(current_app, bind)

    result = engine.execute(statement, params)
    return g.debug_toolbar.render(
        'panels/sqlalchemy_select.html', {
            'result': result.fetchall(),
            'headers': result.keys(),
            'sql': format_sql(statement, params),
            'duration': float(request.args['duration']),
        })
示例#5
0
    def request(self, host, requests):
        server = 'http://%s/jsonrpc' % host

        data = []
        for req in requests:
            method, kwargs = req
            data.append({
                'method': method,
                'params': kwargs,
                'jsonrpc': '2.0',
                'id': method,
            })
        data = json.dumps(data)

        headers = {
            'Content-Type': 'application/json',
        }

        if self.conf('password'):
            base64string = base64.encodestring('%s:%s' % (self.conf('username'), self.conf('password'))).replace('\n', '')
            headers['Authorization'] = 'Basic %s' % base64string

        try:
            log.debug('Sending request to %s: %s', (host, data))
            rdata = self.urlopen(server, headers = headers, params = data, multipart = True)
            response = json.loads(rdata)
            log.debug('Returned from request %s: %s', (host, response))

            return response
        except:
            log.error('Failed sending request to XBMC: %s', traceback.format_exc())
            return []
def sql_explain():
    statement = request.args["sql"]
    params = request.args["params"]
    bind = request.args.get("bind")
    bind = bind if bind != "" else None

    # Validate hash
    hash = hashlib.sha1(current_app.config["SECRET_KEY"] + statement + params).hexdigest()
    if hash != request.args["hash"]:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith("select"):
        return abort(406)

    params = json.loads(params)

    engine = SQLAlchemy().get_engine(current_app, bind)

    if engine.driver == "pysqlite":
        query = "EXPLAIN QUERY PLAN %s" % statement
    else:
        query = "EXPLAIN %s" % statement

    result = engine.execute(query, params)
    return g.debug_toolbar.render(
        "panels/sqlalchemy_explain.html",
        {
            "result": result.fetchall(),
            "headers": result.keys(),
            "sql": format_sql(statement, params),
            "duration": float(request.args["duration"]),
        },
    )
示例#7
0
 def suggest(self, movies = [], ignore = []):
     try:
         data = self.urlopen((self.api_url % ('suggest')) + ','.join(movies) + '/' + ','.join(ignore) + '/')
         suggestions = json.loads(data)
         log.info('Found Suggestions for %s' % (suggestions))
     except Exception, e:
         log.error('Error getting suggestions for %s: %s' % (movies, e))
def facebookloginuser():
    login_credentials = json.loads(request.data)

    fb_id = login_credentials.get('fb_id', None)
    fb_username = login_credentials.get('fb_username', None)
    fb_email = login_credentials.get('fb_email', None)
    fb_token = login_credentials.get('fb_token', None)
    if (fb_id is None):
        return make_errorresponse()
    valid = verify_FBtoken(fb_id, fb_token)
    if (valid):
        user = User.query.filter_by(fb_id=fb_id).first()
        if user is None:
            # Check if the fb_email exists in our DB (user loged in using same email before)
            existingEmail = User.query.filter_by(login_email=fb_email).first()
            if (existingEmail is None) or fb_email:       # no existing user with fb_email or fb_email is null
                registernewuserbyfbID(fb_id, fb_username, fb_email)
            else:    # if there's an existing user with fb_email
                updateUserFacebookID(user, fb_id)
            user = User.query.filter_by(fb_id=fb_id).first()
            if user is not None:
                login_user(user, True)
                token = user.generate_auth_token()
                return make_loginsuccess_response(token, user.alias, user.user_id)
        else:
            login_user(user, True)
            token = user.generate_auth_token()
            return make_loginsuccess_response(token, user.alias, user.user_id)

        return make_errorresponse()
    else:
        return make_fbtoken_notvalid_response()
示例#9
0
    def request(self, host, requests):
        server = "http://%s/jsonrpc" % host

        data = []
        for req in requests:
            method, kwargs = req
            data.append({"method": method, "params": kwargs, "jsonrpc": "2.0", "id": method})
        data = json.dumps(data)

        headers = {"Content-Type": "application/json"}

        if self.conf("password"):
            base64string = base64.encodestring("%s:%s" % (self.conf("username"), self.conf("password"))).replace(
                "\n", ""
            )
            headers["Authorization"] = "Basic %s" % base64string

        try:
            log.debug("Sending request to %s: %s", (host, data))
            rdata = self.urlopen(server, headers=headers, params=data, multipart=True)
            response = json.loads(rdata)
            log.debug("Returned from request %s: %s", (host, response))

            return response
        except:
            log.error("Failed sending request to XBMC: %s", traceback.format_exc())
            return []
示例#10
0
def test_get_product_id(url, client):
    login(client)
    resp = client.get(url, content_type='application/json')
    response_data = json.loads(resp.data)

    assert resp.status_code == 200
    assert Product.get(1).slug == response_data['slug']
示例#11
0
文件: main.py 项目: Arcylus/PBI
 def suggest(self, movies = [], ignore = []):
     try:
         data = self.urlopen(self.urls['suggest'] % (','.join(movies), ','.join(ignore)))
         suggestions = json.loads(data)
         log.info('Found Suggestions for %s', (suggestions))
     except Exception, e:
         log.error('Error getting suggestions for %s: %s', (movies, e))
示例#12
0
def sql_explain():
    statement = request.args['sql']
    params = request.args['params']

    # Validate hash
    hash = hashlib.sha1(current_app.config['SECRET_KEY'] + statement +
                        params).hexdigest()
    if hash != request.args['hash']:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith('select'):
        return abort(406)

    params = json.loads(params)

    engine = SQLAlchemy().get_engine(current_app)

    if engine.driver == 'pysqlite':
        query = 'EXPLAIN QUERY PLAN %s' % statement
    else:
        query = 'EXPLAIN %s' % statement

    result = engine.execute(query, params)
    return g.debug_toolbar.render(
        'panels/sqlalchemy_explain.html', {
            'result': result.fetchall(),
            'headers': result.keys(),
            'sql': format_sql(statement, params),
            'duration': float(request.args['duration']),
        })
示例#13
0
def sql_select():
    statement = request.args['sql']
    params = request.args['params']

    # Validate hash
    hash = hashlib.sha1(
        current_app.config['SECRET_KEY'] + statement + params).hexdigest()
    if hash != request.args['hash']:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith('select'):
        return abort(406)

    params = json.loads(params)

    engine = SQLAlchemy().get_engine(current_app)

    result = engine.execute(statement, params)
    return g.debug_toolbar.render('panels/sqlalchemy_select.html', {
        'result': result.fetchall(),
        'headers': result.keys(),
        'sql': format_sql(statement, params),
        'duration': float(request.args['duration']),
    })
示例#14
0
文件: main.py 项目: babbel4ever/PBI
    def notify(self, message = '', data = {}, listener = None):
        if self.isDisabled(): return

        try:
            params = {
                'label': self.default_title,
                'msg': toUnicode(message),
            }

            headers = {
                'Authorization': "Basic %s" % base64.encodestring('%s:%s' % (self.conf('username'), self.conf('api_key')))[:-1]
            }

            handle = self.urlopen(self.url, params = params, headers = headers)
            result = json.loads(handle)

            if result['status'] != 'success' or result['response_message'] != 'OK':
                raise Exception

        except:
            log.error('Notification failed: %s', traceback.format_exc())
            return False

        log.info('Notifo notification successful.')
        return True
示例#15
0
def test_addresses_put_not_valid_data(url, client):
    uid = json.loads(login(client).data)['uid']
    address_data = first_address.copy()
    del address_data['city']
    resp = client.put(url, data=json.dumps(address_data),
                      content_type='application/json')
    assert resp.status_code == 404
    logout(client, uid)
示例#16
0
    def releaseDate(self, imdb_id):

        try:
            data = self.urlopen((self.apiUrl % ('eta')) + (id + '/'))
            dates = json.loads(data)
            log.info('Found ETA for %s: %s' % (imdb_id, dates))
        except Exception, e:
            log.error('Error getting ETA for %s: %s' % (imdb_id, e))
示例#17
0
 def suggest(self, movies=[], ignore=[]):
     try:
         data = self.urlopen(self.urls['suggest'] %
                             (','.join(movies), ','.join(ignore)))
         suggestions = json.loads(data)
         log.info('Found Suggestions for %s', (suggestions))
     except Exception, e:
         log.error('Error getting suggestions for %s: %s', (movies, e))
示例#18
0
    def releaseDate(self, imdb_id):

        data = self.urlopen(self.apiUrl % ('eta', id))

        try:
            dates = json.loads(data)
            log.info('Found ETA for %s: %s' % (imdb_id, dates))
        except Exception, e:
            log.error('Error getting ETA for %s: %s' % (imdb_id, e))
示例#19
0
 def get_data_from_request(self, req, data_schema):
     if (req.data is None) or (req.data == ''):
         return None
     try:
         d = json.loads(req.data)
         validate(d, data_schema)
         return d
     except Exception as e:
         return None
示例#20
0
文件: main.py 项目: Arcylus/PBI
    def getReleaseDate(self, identifier = None):

        if identifier is None: return {}
        try:
            data = self.urlopen(self.urls['eta'] % identifier, headers = self.getRequestHeaders())
            dates = json.loads(data)
            log.debug('Found ETA for %s: %s', (identifier, dates))
            return dates
        except Exception, e:
            log.error('Error getting ETA for %s: %s', (identifier, e))
示例#21
0
    def getReleaseDate(self, identifier=None):

        if identifier is None: return {}
        try:
            data = self.urlopen(self.urls['eta'] % identifier,
                                headers=self.getRequestHeaders())
            dates = json.loads(data)
            log.debug('Found ETA for %s: %s', (identifier, dates))
            return dates
        except Exception, e:
            log.error('Error getting ETA for %s: %s', (identifier, e))
示例#22
0
def verify_FBtoken(fb_id, token):
    bret = False
    params = {'fields': 'id', 'access_token': token}
    response = requests.get("https://graph.facebook.com/me", params=params)
    json_data = json.loads(response.text)
    if(response.status_code == 200):
        response_id = json_data["id"]
        if(response_id == fb_id):
            bret = True

    return bret
示例#23
0
    def getReleaseDate(self, identifier = None):

        if identifier is None: return {}
        try:
            headers = {'X-CP-Version': fireEvent('app.version', single = True)}
            data = self.urlopen((self.api_url % ('eta')) + (identifier + '/'), headers = headers)
            dates = json.loads(data)
            log.debug('Found ETA for %s: %s' % (identifier, dates))
            return dates
        except Exception, e:
            log.error('Error getting ETA for %s: %s' % (identifier, e))
示例#24
0
    def getMeta(self, filename):
        lib_dir = os.path.join(Env.get('app_dir'), 'libs')
        script = os.path.join(lib_dir, 'getmeta.py')

        p = subprocess.Popen(["python", script, filename], stdout = subprocess.PIPE, stderr = subprocess.PIPE, cwd = lib_dir)
        z = p.communicate()[0]

        try:
            meta = json.loads(z)
            return meta
        except Exception:
            log.error('Couldn\'t get metadata from file: %s' % traceback.format_exc())
示例#25
0
    def getReleaseDate(self, identifier=None):

        if identifier is None: return {}
        try:
            headers = {'X-CP-Version': fireEvent('app.version', single=True)}
            data = self.urlopen((self.api_url % ('eta')) + (identifier + '/'),
                                headers=headers)
            dates = json.loads(data)
            log.debug('Found ETA for %s: %s', (identifier, dates))
            return dates
        except Exception, e:
            log.error('Error getting ETA for %s: %s', (identifier, e))
示例#26
0
def test_product_create(url, client):
    data = first_product.copy()

    login(client)
    resp = client.post(url, content_type='application/json')
    assert resp.status_code == 400

    resp = client.post(url, data=json.dumps(data),
                       content_type='application/json')

    assert resp.status_code == 201
    assert 'slug' in json.loads(resp.data)
示例#27
0
文件: main.py 项目: Arcylus/PBI
    def search(self, q, limit = 12):

        cache_key = 'cpapi.cache.%s' % q
        cached = self.getCache(cache_key, self.urls['search'] % tryUrlencode(q), timeout = 3, headers = self.getRequestHeaders())

        if cached:
            try:
                movies = json.loads(cached)
                return movies
            except:
                log.error('Failed parsing search results: %s', traceback.format_exc())

        return []
示例#28
0
def get_productswithid():
    """ Gets the array of product infos with the product ids 
    """
    try:
        product_idlist = json.loads(request.data)
    except ValueError as e:
        return utility.get_response_for_code(utility.ERROR_BADINPUT)
    collection = mongoclient_manager.getdb('joytube_infodb').products
    resultlist = find_all_from_mongodb(collection, {"product_id": { "$in": product_idlist }})
    if len(resultlist) == 0:
        return utility.get_response_for_code(utility.ERROR_NOTFOUND)
    response = make_response(json.dumps(resultlist))
    response.headers['Content-Type'] = 'application/json'
    return response
示例#29
0
def put_facebook_updates():
    """
    (POST: social_connect/facebook/updates)
    """
    from unifide_backend.action.social.facebook.action import page_realtime_update

    data = json.loads(request.data)
    object = data["object"]
    entry = data["entry"]

    if object == "page":
        page_realtime_update(entry)

    return jsonify({"status": "ok"})
示例#30
0
def test_authorization(url, client):
    client.get(url)
    user = User.query.filter_by(email='*****@*****.**').first()
    assert user is not None
    user.set_password('test').save()

    # assert session['is_anonymous'] == True

    resp = login(client, '*****@*****.**', 'test')
    j_resp = json.loads(resp.data)

    assert 'uid' in j_resp
    assert isinstance(session['uid'], long)
    assert session['is_anonymous'] == False
示例#31
0
def pwd_reset_request():
    login_credentials = json.loads(request.data)
    login_email = login_credentials.get('login_email', None)
    if (login_email is None):
        return make_errorresponse()

    user = User.query.filter_by(login_email=login_email).first()
    if user:
        token = user.generate_reset_token()
        send_email(user.login_email, 'Reset your password on joyTu.be',
                            'auth/email/reset_password',
                            user=user, token=token,
                            next=request.args.get('next'))
    return make_successresponse()
示例#32
0
def signupuser():
    login_credentials = json.loads(request.data)
    login_email = login_credentials.get('username', None)
    login_password = login_credentials.get('password', None)
    if (login_email is None) or (login_password is None):
        return make_errorresponse()
    user = User.query.filter_by(login_email=login_email).first()
    if user is None:
        registernewuser(login_email, login_password)
        user = User.query.filter_by(login_email=login_email).first()
        if user is not None:
            login_user(user, True)
            token = user.generate_auth_token()
            return make_loginsuccess_response(token, user.alias, user.user_id)
    return make_errorresponse()
示例#33
0
    def search(self, q, limit=12):

        cache_key = 'cpapi.cache.%s' % q
        cached = self.getCache(cache_key,
                               self.urls['search'] % tryUrlencode(q),
                               headers=self.getRequestHeaders())

        if cached:
            try:
                movies = json.loads(cached)
                return movies
            except:
                log.error('Failed parsing search results: %s',
                          traceback.format_exc())

        return []
示例#34
0
文件: main.py 项目: Arcylus/PBI
    def getInfo(self, identifier = None):

        if not identifier:
            return

        cache_key = 'cpapi.cache.info.%s' % identifier
        cached = self.getCache(cache_key, self.urls['info'] % identifier, timeout = 3, headers = self.getRequestHeaders())

        if cached:
            try:
                movie = json.loads(cached)
                return movie
            except:
                log.error('Failed parsing info results: %s', traceback.format_exc())

        return {}
示例#35
0
    def getMeta(self, filename):
        lib_dir = os.path.join(Env.get('app_dir'), 'libs')
        script = os.path.join(lib_dir, 'getmeta.py')

        p = subprocess.Popen(["python", script, filename],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             cwd=lib_dir)
        z = p.communicate()[0]

        try:
            meta = json.loads(z)
            return meta
        except Exception:
            log.error('Couldn\'t get metadata from file: %s' %
                      traceback.format_exc())
示例#36
0
    def getInfo(self, identifier=None):

        if not identifier:
            return

        cache_key = 'cpapi.cache.info.%s' % identifier
        cached = self.getCache(cache_key,
                               self.urls['info'] % identifier,
                               headers=self.getRequestHeaders())

        if cached:
            try:
                movie = json.loads(cached)
                return movie
            except:
                log.error('Failed parsing info results: %s',
                          traceback.format_exc())

        return {}
示例#37
0
def oauth_authorize_post(provider = ""):
    #print "current_user: "******"":
        provider    = authorize_details.get('provider', None)
        next        = authorize_details.get('next', None)
        video_id = authorize_details.get('video_id', None)
        if video_id != "":
            add_bookmark_data["video_id"]                   = video_id
            add_bookmark_data["product_id"]                 = authorize_details.get('product_id', None)
            add_bookmark_data["object_id"]                  = authorize_details.get('object_id', None)
            add_bookmark_data["video_current_time_in_ms"]   = authorize_details.get('video_current_time_in_ms', None)
            add_bookmark_data["roi_group_id"]               = authorize_details.get('roi_group_id', None)

    return oauth_authorize(provider, next, add_bookmark_data)
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.secret_key = 'fd{He5<95f9e396.5d101O<!d5a2a09fRa1a8'
    app.config['CLIENT_ID'] = json.loads(open('client_secrets.json', 'r').read())['web']['client_id']
    config[config_name].init_app(app)

    app.jinja_env.filters['v_duration'] = v_duration_filter
    #app.jinja_env.filters['v_username'] = v_username_filter

    bootstrap.init_app(app)
    moment.init_app(app)
    mail.init_app(app)
    mongoclient_manager.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

#     if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
#         from flask.ext.sslify import SSLify
#         sslify = SSLify(app)

    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from account import account_page as account_blueprint 
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    
    from video import video_page as video_blueprint
    app.register_blueprint(video_blueprint, url_prefix='/video')
    
    from loginman import loginman_page as loginman_blueprint
    app.register_blueprint(loginman_blueprint)

    from api import apiblueprint
    app.register_blueprint(apiblueprint, url_prefix='/api')

    from info import infoblueprint
    app.register_blueprint(infoblueprint, url_prefix='/info')
    
    return app
示例#39
0
def put_user():
    """
    (PUT: user)
    """
    _id = coerce_bson_id(request.form.get("_id"))
    username = request.form.get("username")
    email = request.form.get("email")
    password = request.form.get("password")
    first_name = request.form.get("first_name")
    middle_name = request.form.get("middle_name")
    last_name = request.form.get("last_name")
    address = request.form.get("address")
    user_groups = json.loads(request.form.get("user_groups"))
    status = request.form.get("status")

    new_user(_id, address, email, first_name, last_name, middle_name, password, status, user_groups, username)

    return jsonify({
        "status": "ok",
    })
示例#40
0
    def post(self, collection):
        """
        Route : POST /<collection>/
        Description : Creates a list of documents in the database.
        Returns status and _id for each document.
        """

        if not self.app.config['COLLECTION_POST']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED",
                              "Accepted media type : application/json")
        data = request.data
        if not data:
            return send_error(400, "EMPTY_DATA")
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        if isinstance(data, dict):
            status = self.validate(data, collection)
            if status['created']:
                base_url = request.base_url
                response = {'title': "Document created", 'links': []}
                response['links'].append(
                    get_self_link(title=self.app.DOMAINS[collection]['title'],
                                  base_url=base_url,
                                  description='You are here.',
                                  methods=["GET", "POST", "DELETE"]))
                response['links'].append(
                    get_document_link(status['document'], base_url))
                return send_response(response, 201,
                                     get_etag(status['document']))
            else:
                return send_error(400, "VALIDATION_ERROR", status['issues'])
        return send_error(400, "BAD_DATA_FORMAT")
示例#41
0
    def request(self, host, requests):
        server = 'http://%s/jsonrpc' % host

        data = []
        for req in requests:
            method, kwargs = req
            data.append({
                'method': method,
                'params': kwargs,
                'jsonrpc': '2.0',
                'id': method,
            })
        data = json.dumps(data)

        headers = {
            'Content-Type': 'application/json',
        }

        if self.conf('password'):
            base64string = base64.encodestring(
                '%s:%s' %
                (self.conf('username'), self.conf('password'))).replace(
                    '\n', '')
            headers['Authorization'] = 'Basic %s' % base64string

        try:
            log.debug('Sending request to %s: %s', (host, data))
            rdata = self.urlopen(server,
                                 headers=headers,
                                 params=data,
                                 multipart=True)
            response = json.loads(rdata)
            log.debug('Returned from request %s: %s', (host, response))

            return response
        except:
            log.error('Failed sending request to XBMC: %s',
                      traceback.format_exc())
            return []
示例#42
0
文件: items.py 项目: miandreu/madame
    def put(self, collection, id):
        """
        Route : PUT /<collection>/<id>
        Description : Updates the document.
        Returns the status.
        """

        if not self.app.config['ITEM_PUT']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id": id})
        date_utc = datetime.utcnow()
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED",
                              "Accepted media type : application/json")
        data = request.data
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        for key in data:
            document[key] = data[key]
        copy = {}
        for key in document:
            if key == "created": continue
            if key == "updated": continue
            if key == "_id": continue
            copy[key] = document[key]
        v = Validator()
        if v.validate(copy, self.app.DOMAINS[collection]['schema']):
            document['updated'] = date_utc
            self.mongo.db[collection].save(document)
            return send_response(status=200)
        return send_error(400, "VALIDATION_ERROR", v.error)