Python flask.json.dumps() Examples

The following are code examples for showing how to use flask.json.dumps(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: geo-knowledge-hub   Author: geosec   File: views.py    MIT License 6 votes vote down vote up
def index():
    """REST API root endpoint."""
    return Response(
        json.dumps(
            {
                'links': {
                    'resources': {
                        'deposits': url_for(
                            'invenio_deposit_rest.depid_list', _external=True),
                        'records': url_for(
                            'invenio_records_rest.resid_list', _external=True),
                    }
                }
            }
        ),
        mimetype='application/json',
    ) 
Example 2
Project: RTX   Author: RTXteam   File: test_query_controller.py    MIT License 6 votes vote down vote up
def test_query(self):
        """Test case for query

        Query reasoner via one of several inputs
        """
        request_body = None
        headers = { 
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
        response = self.client.open(
            '/api/rtx/v1/query',
            method='POST',
            headers=headers,
            data=json.dumps(request_body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example 3
Project: beavy   Author: beavyHQ   File: __init__.py    Mozilla Public License 2.0 6 votes vote down vote up
def api_only(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        accepted = set(request.accept_mimetypes.values())
        explicit = not(not request.args.get("json", False))
        if not (accepted & API_MIMETYPES) and not explicit:
            return abort(415, "Unsupported Media Type")

        resp = fn(*args, **kwargs)
        if not isinstance(resp, ResponseBase):
            data, code, headers = unpack(resp)
            # we've found one, return json
            if isinstance(data, MarshalResult):
                data = data.data
            resp = make_response(json.dumps(data,
                                            indent=explicit and 4 or 0),
                                 code)

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = 'application/json'
        return resp
    return wrapped 
Example 4
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 6 votes vote down vote up
def get_user_portfolio_list():
    '''
    Returns the available user portfolio names in the Investment Portfolio service.
    Uses type='user_portfolio' to specify.
    '''
    names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','user_portfolio')
    p = json.loads(json.dumps(res))
    try:
        for a in p['portfolios']:
            names.append(a['name'])
        #Gather only unique names, as there's likely history for the benchmarks.
        names = list(set(names))
        return names
    except:
        return names 
Example 5
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 6 votes vote down vote up
def get_benchmark_list():
    '''
    Returns the available benchmark portfolio names in the Investment Portfolio service.
    Uses type='bechmark' to specify.
    '''
    names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','benchmark')
    p = json.loads(json.dumps(res))
    try:
        for b in p['portfolios']:
            names.append(b['name'])
        #Gather only unique names, as there's likely history for the benchmarks.
        names = list(set(names))
        return names
    except:
        return names 
Example 6
Project: invenio-records-rest   Author: inveniosoftware   File: json.py    MIT License 6 votes vote down vote up
def serialize_search(self, pid_fetcher, search_result, links=None,
                         item_links_factory=None, **kwargs):
        """Serialize a search result.

        :param pid_fetcher: Persistent identifier fetcher.
        :param search_result: Elasticsearch search result.
        :param links: Dictionary of links to add to response.
        """
        total = search_result['hits']['total'] if lt_es7 else \
            search_result['hits']['total']['value']
        return json.dumps(dict(
            hits=dict(
                hits=[self.transform_search_hit(
                    pid_fetcher(hit['_id'], hit['_source']),
                    hit,
                    links_factory=item_links_factory,
                    **kwargs
                ) for hit in search_result['hits']['hits']],
                total=total,
            ),
            links=links or {},
            aggregations=search_result.get('aggregations', dict()),
        ), **self._format_args()) 
Example 7
Project: MegaQC   Author: ewels   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def distributions():
    # Get the fields from the add-new-filters form
    return_data = aggregate_new_parameters(current_user, [], False)
    sample_filters = order_sample_filters()
    return render_template(
        'public/distributions.html',
        db = db,
        User = User,
        user_token = current_user.api_token,
        sample_filters = sample_filters,
        num_samples = return_data[0],
        report_fields = return_data[1],
        sample_fields = return_data[2],
        report_fields_json = json.dumps(return_data[1]),
        sample_fields_json = json.dumps(return_data[2])
        ) 
Example 8
Project: MegaQC   Author: ewels   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def trends():
    # Get the fields from the add-new-filters form
    return_data = aggregate_new_parameters(current_user, [], False)
    sample_filters = order_sample_filters()
    return render_template(
        'public/trends.html',
        db = db,
        User = User,
        user_token = current_user.api_token,
        sample_filters = sample_filters,
        num_samples = return_data[0],
        report_fields = return_data[1],
        sample_fields = return_data[2],
        report_fields_json = json.dumps(return_data[1]),
        sample_fields_json = json.dumps(return_data[2])
        ) 
Example 9
Project: MegaQC   Author: ewels   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def comparisons():
    # Get the fields from the add-new-filters form
    return_data = aggregate_new_parameters(current_user, [], False)
    sample_filters = order_sample_filters()
    return render_template(
        'public/comparisons.html',
        db = db,
        User = User,
        user_token = current_user.api_token,
        sample_filters = sample_filters,
        num_samples = return_data[0],
        report_fields = return_data[1],
        sample_fields = return_data[2],
        report_fields_json = json.dumps(return_data[1]),
        sample_fields_json = json.dumps(return_data[2])
        ) 
Example 10
Project: sam-s-club-auctions   Author: sameer2800   File: app.py    Apache License 2.0 6 votes vote down vote up
def createTweet():
	if request.headers['Content-Type'] == 'application/json':		
		inputData = request.json
		auction_id = inputData["auction_id"]
		product_name = inputData["product_name"]
		image_url = inputData["image_url"]
		cur_bidding_price = inputData["cur_bidding_price"]		
		auction_end_time = inputData["auction_end_time"]
		status_id = create_tweet(api,auction_id,product_name,image_url,cur_bidding_price,auction_end_time)
		data = {}
		data['tweet_id'] = status_id
		json_data = json.dumps(data)
		return json_data

		

#@app.route('/auction/parse-tweet', methods=['POST'])    
#def parseTweet(): 
Example 11
Project: selene-backend   Author: MycroftAI   File: skill_settings.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, skill_family_name):
        """Process an HTTP GET request"""
        self._authenticate()
        self.family_settings = self.setting_repository.get_family_settings(
            self.account.id,
            skill_family_name
        )
        self._parse_selection_options()
        response_data = self._build_response_data()

        # The response object is manually built here to bypass the
        # camel case conversion so settings are displayed correctly
        return Response(
            response=json.dumps(response_data),
            status=HTTPStatus.OK,
            content_type='application/json'
        ) 
Example 12
Project: Product-Info-Crawler   Author: aishmittal   File: views.py    MIT License 6 votes vote down vote up
def search_results():
    if request.method == 'POST':
          os.system('python '+crawlerFile+' '+ request.json['product'])
          print 'Crawling Completed'
          title=[]
          image=[]
          price=[]
          url=[]
          source=[]
          with open(resultFile) as f:
            records = csv.DictReader(f)
            for row in records:
                title.append(row['product_name'])
                image.append(row['image_url'])
                price.append(row['price'])
                url.append(row['product_url'])
                source.append(row['source'])
          data=dict({'product_name':title,'image_url':image,'price':price,'product_url':url,'source':source})
          response = app.response_class(
            response=json.dumps(data, cls=MyEncoder),
            status=200,
            mimetype='application/json'
        )
          return response 
Example 13
Project: Python24   Author: HaoZhang95   File: demo1.py    MIT License 6 votes vote down vote up
def demo4():

    json_dict = {
        'name': 'zhangsan',
        'age': 18

    }

    # 使用falsk.json包下的dumps方法把一个字典对象转换为json格式的字符串
    json_str = json.dumps(json_dict)

    # 使用laod方法把json格式的字符串转换为一个字典对象
    # dict_obj = json.load('{ "name": "zhangsan","age": 18}')

    # json.dunps返回的json字符串在浏览器中Content-type是text/html
    # 但是使用jsonify来处理字典对象的话返回的也是str,但是浏览器的content-type就变成了application/json
    return jsonify(json_dict)


# 直接使用redirect函数进行重定向
# 重定向的反向解析:使用重定向路由的视图函数名字url_for(XXX),并且携带参数 
Example 14
Project: ZaaS   Author: kakugirai   File: run.py    MIT License 6 votes vote down vote up
def api_message():
    if request.headers['Content-Type'] == 'application/json':
        # Read request
        data = request.json
        # Save different types of data to different dirs
        dir_today = time.strftime("%m-%d-%Y")
        dirs = ["json", "html", "pdf"]
        # Create dir if not exists
        for dirname in dirs:
            if not os.path.exists(os.path.join(dirname, dir_today)):
                os.makedirs(os.path.join(dirname, dir_today))
        # Deprive login name in data
        data_without_login_name = {
            key: value for key, value in data.items() if value is not data["login_name"]}
        # Wirte json file
        with open(os.path.join("json", dir_today, data["login_name"] + ".json"), "w+") as json_file:
            json_file.write(json.dumps(data_without_login_name))
        # print data["login_name"] + ".json created"
        return data["login_name"] + ".json created"
    else:
        return "415 Unsupported Media Type" 
Example 15
Project: flask-smorest   Author: marshmallow-code   File: etag.py    MIT License 6 votes vote down vote up
def _generate_etag(etag_data, etag_schema=None, extra_data=None):
        """Generate an ETag from data

        etag_data: Data to use to compute ETag
        etag_schema: Schema to dump data with before hashing
        extra_data: Extra data to add before hashing

        Typically, extra_data is used to add pagination metadata to the hash.
        It is not dumped through the Schema.
        """
        if etag_schema is None:
            raw_data = etag_data
        else:
            if isinstance(etag_schema, type):
                etag_schema = etag_schema()
            raw_data = etag_schema.dump(etag_data)
            if MARSHMALLOW_VERSION_MAJOR < 3:
                raw_data = raw_data.data
        if extra_data:
            raw_data = (raw_data, extra_data)
        # flask's json.dumps is needed here
        # as vanilla json.dumps chokes on lazy_strings
        data = json.dumps(raw_data, sort_keys=True)
        return hashlib.sha1(bytes(data, 'utf-8')).hexdigest() 
Example 16
Project: Portfolio-compute   Author: IBM   File: run.py    Apache License 2.0 6 votes vote down vote up
def get_unit_test_portfolios():
    '''
    Returns the available user portfolio names in the Investment Portfolio service.
    Uses type='user_portfolio' to specify.
    '''
    portfolio_names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','unit test portfolio')
    try:
        for portfolios in res['portfolios']:
            portfolio_names.append(portfolios['name'])
        #returns the portfolio names as list
        print("Portfolio_names:" + str(portfolio_names))
        return json.dumps(portfolio_names)
    except:
        return "No portfolios found."

#Deletes all unit test holdings and portfolios for cleanup 
Example 17
Project: stop2.0-backend   Author: STOP2   File: stop.py    MIT License 6 votes vote down vote up
def stoprequests():
    if request.method == 'GET':
        request_id = request.args.get('request_id')
        if not request_id:
            resp = make_response(json.dumps({'error': 'no request_id query parameter given'}), 400)
            resp.mimetype = 'application/json'
            return resp
        resp = make_response(json.dumps(digitransitAPIService.get_request_info(request_id)))
        resp.mimetype = 'application/json'
        return resp
    elif request.method == 'POST':
        json_data = request.json
        trip_id = json_data.get('trip_id')
        stop_id = json_data.get('stop_id')
        device_id = json_data.get('device_id', '0')
        push_notification = json_data.get('push_notification', True)
        if not (trip_id and stop_id):
            resp = make_response(json.dumps({'error': 'no trip_id or stop_id query parameter given'}), 400)
            resp.mimetype = 'application/json'
            return resp
        resp = make_response(json.dumps(digitransitAPIService.make_request(trip_id, stop_id, device_id, push_notification)))
        resp.mimetype = 'application/json'
        return resp 
Example 18
Project: flasky   Author: RoseOu   File: widgets.py    MIT License 5 votes vote down vote up
def recaptcha_html(self, server, query, options):
        html = current_app.config.get('RECAPTCHA_HTML', RECAPTCHA_HTML)
        return Markup(html % dict(
            script_url='%schallenge?%s' % (server, query),
            frame_url='%snoscript?%s' % (server, query),
            options=json.dumps(options, cls=_JSONEncoder)
        )) 
Example 19
Project: ras-frontstage   Author: ONSdigital   File: message_get.py    MIT License 5 votes vote down vote up
def _get_message_json(form, first_message_in_conversation, msg_to, msg_from):

    return json.dumps({
        'msg_from': msg_from,
        'msg_to': msg_to,
        'subject': form.subject.data,
        'body': form.body.data,
        'thread_id': first_message_in_conversation['thread_id'],
        'collection_case': "",
        'survey': first_message_in_conversation['survey_id'],
        'business_id': first_message_in_conversation['ru_ref']}) 
Example 20
Project: bendercoin   Author: matejcik   File: transaction.py    MIT License 5 votes vote down vote up
def hash(self):
        inp = [attr.asdict(i) for i in self.inputs]
        out = [attr.asdict(o) for o in self.outputs]
        hashables = dict(inputs=inp, outputs=out, message=self.message)
        data = json.dumps(hashables, sort_keys=True)
        return sha256(data.encode("utf-8")).digest() 
Example 21
Project: bendercoin   Author: matejcik   File: util.py    MIT License 5 votes vote down vote up
def print_json(j):
    try:
        if isinstance(j, requests.Response):
            j = j.json()
        s = json.dumps(j, sort_keys=True, indent=4)
        print(s)
    except Exception as e:
        print("could not decode json:", e)
        print(j) 
Example 22
Project: LOST   Author: kylemh   File: api.py    MIT License 5 votes vote down vote up
def revoke_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])
        print('This is the api_req', api_req)

        # If http request is missing a parameter...
        if 'username' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameter(s)'})
            return error_result

        # All parameters present in request.
        username = api_req['username']

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = helpers.db_query(matching_user, [username])

        # If user exists in database, deactivate user; otherwise, return "User Not Found" API Error.
        if user_does_exist:
            deactivate_existing_user = ("UPDATE users SET active = FALSE "
                                        "WHERE username = %s")
            helpers.db_change(deactivate_existing_user, [username])

            data = json.dumps({'result': 'OK'})
            return data
        else:
            error_result = json.dumps({'result': 'Error: User Not Found'})
            return error_result 
Example 23
Project: LOST   Author: kylemh   File: api.py    MIT License 5 votes vote down vote up
def revoke_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])
        print('This is the api_req', api_req)

        # If http request is missing a parameter...
        if 'username' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameter(s)'})
            return error_result


        # All parameters present in request.
        username = api_req['username']

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = db_query(matching_user, [username])

        # If user exists in database, deactivate user; otherwise, return "User Not Found" API Error.
        if user_does_exist:
            deactivate_existing_user = ("UPDATE users SET active = FALSE "
                                        "WHERE username = %s")
            db_change(deactivate_existing_user, [username])

            data = json.dumps({'result': 'OK'})
            return data
        else:
            error_result = json.dumps({'result': 'Error: User Not Found'})
            return error_result 
Example 24
Project: jenca-authentication   Author: bimlauncher   File: authentication.py    MIT License 5 votes vote down vote up
def signup():
    """
    Sign up a new user.

    :param email: The email address of the new user.
    :type email: string
    :param password: A password to associate with the given ``email`` address.
    :type password: string
    :reqheader Content-Type: application/json
    :resheader Content-Type: application/json
    :resjson string email: The email address of the new user.
    :resjson string password: The password of the new user.
    :status 200: A user with the given ``email`` and ``password`` has been
        created.
    :status 409: There already exists a user with the given ``email``.
    """
    email = request.json['email']
    password = request.json['password']

    if load_user_from_id(email) is not None:
        return jsonify(
            title='There is already a user with the given email address.',
            detail='A user already exists with the email "{email}"'.format(
                email=email),
        ), codes.CONFLICT

    data = {
        'email': email,
        'password_hash': bcrypt.generate_password_hash(password).decode(
            'utf8'),
    }

    requests.post(
        urljoin(STORAGE_URL, '/users'),
        headers={'Content-Type': 'application/json'},
        data=json.dumps(data),
    )

    return jsonify(email=email, password=password), codes.CREATED 
Example 25
Project: hdxscraper-world-bank-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def post_data(self, data, table):
        # returns status_code 201
        url = base + table
        r = self.client.post(url, data=dumps(data), content_type=self.json)
        return r 
Example 26
Project: hdxscraper-world-bank-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def patch_data(self, data, table, id=None, query=None):
        # returns status_code 200 or 201
        if id:
            url = base + table + '/' + id
        else:
            url = base + table

        if query:
            r = self.client.patch(
                url, data=dumps(data), content_type=self.json, q=query)
        else:
            r = self.client.patch(url, data=dumps(data), content_type=self.json)

        return r 
Example 27
Project: RTX   Author: RTXteam   File: test_result_controller.py    MIT License 5 votes vote down vote up
def test_post_result_feedback(self):
        """Test case for post_result_feedback

        Store feedback for a particular result
        """
        body = Feedback()
        response = self.client.open(
            '/api/rtx/v1/result/{result_id}/feedback'.format(result_id=56),
            method='POST',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example 28
Project: RTX   Author: RTXteam   File: test_query_controller.py    MIT License 5 votes vote down vote up
def test_query(self):
        """Test case for query

        Query RTX via one of several inputs
        """
        body = Query()
        response = self.client.open(
            '/api/rtx/v1/query',
            method='POST',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example 29
Project: RTX   Author: RTXteam   File: test_translate_controller.py    MIT License 5 votes vote down vote up
def test_translate(self):
        """Test case for translate

        Translate natural language question into a standardized query
        """
        body = Question()
        response = self.client.open(
            '/api/rtx/v1/translate',
            method='POST',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example 30
Project: RTX   Author: RTXteam   File: test_result_controller.py    MIT License 5 votes vote down vote up
def test_post_result_feedback(self):
        """Test case for post_result_feedback

        Store feedback for a particular result
        """
        feedback = {
  "commenter_id" : 1,
  "datetime" : "2018-05-08 12:00",
  "rating_id" : 1,
  "result_id" : "https://rtx.ncats.io/api/rtx/v1/result/234",
  "expertise_level_id" : 1,
  "comment" : "This is a great result because...",
  "id" : "https://rtx.ncats.io/api/rtx/v1/result/234/feedback/56",
  "commenter_full_name" : "John Smith"
}
        headers = { 
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
        response = self.client.open(
            '/api/rtx/v1/result/{result_id}/feedback'.format(result_id=56),
            method='POST',
            headers=headers,
            data=json.dumps(feedback),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example 31
Project: beavy   Author: beavyHQ   File: app.py    Mozilla Public License 2.0 5 votes vote down vote up
def inject_messages():
    return dict(MESSAGES=json.dumps(get_messages())) 
Example 32
Project: beavy   Author: beavyHQ   File: __init__.py    Mozilla Public License 2.0 5 votes vote down vote up
def fallbackRender(template, key=None):

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            resp = fn(*args, **kwargs)
            if isinstance(resp, ResponseBase):
                return resp

            data, code, headers = unpack(resp)

            accepted = set(request.accept_mimetypes.values())
            explicit = not (not request.args.get("json", False))
            if len(accepted & API_MIMETYPES) or explicit:
                # we've found one, return json
                if isinstance(data, MarshalResult):
                    data = data.data
                resp = make_response(json.dumps(data,
                                                indent=explicit and 4 or 0),
                                     code)
                ct = 'application/json'
            else:
                resp = make_response(render_template(template,
                                                     key=key,
                                                     data=data),
                                     code)
                ct = "text/html"

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = ct
            return resp

        return decorated_view
    return wrapper 
Example 33
Project: Health-Checker   Author: KriAga   File: tag.py    MIT License 5 votes vote down vote up
def dumps(self, value):
        """Tag the value and dump it to a compact JSON string."""
        return dumps(self.tag(value), separators=(',', ':')) 
Example 34
Project: slot   Author: nhshd-slot   File: controller.py    MIT License 5 votes vote down vote up
def render_new_procedure_form():
    if request.method == 'POST':
        print(request.form)
        opportunity_doctor = request.form['doctor']
        opportunity_procedure = request.form['procedure']
        opportunity_location = request.form['location']
        opportunity_duration = request.form['duration']

        opportunity = {
            'doctor': opportunity_doctor,
            'procedure': opportunity_procedure,
            'location': opportunity_location,
            'duration': opportunity_duration
        }

        print(opportunity)
        ref_id, new_op = db_fieldbook.add_opportunity(opportunity)

        expiry_time = datetime.datetime.fromtimestamp(new_op['expiry_time']).strftime("%H:%M")

        number_messages_sent, message_ref = messaging.broadcast_procedure(opportunity_procedure,
                                                                          opportunity_location,
                                                                          opportunity_doctor,
                                                                          ref_id,
                                                                          expiry_time)

        offer = db_fieldbook.add_offer(ref_id, number_messages_sent)
        print(offer['id'])

        print(json.dumps(opportunity))

        return redirect('/dashboard', code=302)

    else:
        procedures = db_fieldbook.get_procedures()
        locations = db_fieldbook.get_locations()
        timeframes = db_fieldbook.get_timeframes()
        doctors = db_fieldbook.get_doctors()
        return render_template('new_procedure.html', procedures=procedures, locations=locations,
                               timeframes=timeframes, doctors=doctors) 
Example 35
Project: recruit   Author: Frank-qlu   File: tag.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, value):
        """Tag the value and dump it to a compact JSON string."""
        return dumps(self.tag(value), separators=(',', ':')) 
Example 36
Project: lite-python   Author: Paybook   File: utilities.py    MIT License 5 votes vote down vote up
def get_json(self):
		error_json = self.content
		return json.dumps(error_json) 
Example 37
Project: lite-python   Author: Paybook   File: utilities.py    MIT License 5 votes vote down vote up
def get_json(self):
		success_json = self.content
		return json.dumps(success_json) 
Example 38
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 5 votes vote down vote up
def init():
    '''
    Populates investment portfolio with universe, benchmark(s), and current portfolio(s).
    Also populates variables needed for the drop-downs like what attributes to consider.
    '''
    #configure instrument universe - the total set of instruments to be considered in the analysis.
    instrumentUniverse,iu_holdings = initialize.universe_from_csv()
    res = investmentportfolio.Create_Portfolio(instrumentUniverse)
    #add initial set of holdings to instrument universe
    res = investmentportfolio.Create_Portfolio_Holdings('instrument_universe',iu_holdings)

    #configure benchmark portfolios
    benchmarks = initialize.benchmarks_from_csv()
    for b in benchmarks:
        res = investmentportfolio.Create_Portfolio(b[0])
        #add initial set of holdings to benchmark
        res = investmentportfolio.Create_Portfolio_Holdings(b[0]['name'],b[1])

    #configure initial portfolio
    my_portfolio,mp_holdings  = initialize.portfolio_from_csv()
    res = investmentportfolio.Create_Portfolio(my_portfolio)
    #add initial set of holdings to my portfolio
    res = investmentportfolio.Create_Portfolio_Holdings(my_portfolio['name'],mp_holdings)

    return Response(json.dumps(res), mimetype='application/json')

#Deletes all holdings and portfolios for cleanup 
Example 39
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 5 votes vote down vote up
def load():
    '''
    Populates investment portfolio with universe, benchmark(s), and current portfolio(s).
    Also populates variables needed for the drop-downs like what attributes to consider.
    '''
    constraints = parse_universe()
    data ={
        'user_portfolios':get_user_portfolio_list(),
        'benchmark_portfolios':get_benchmark_list(),
        'hard_constraints':constraints['hard_constraints'],
        'esg_constraints':constraints['esg_constraints'],
        'allocation_constraints':constraints['allocation_constraints']
    }
    return Response(json.dumps(data, indent=4,sort_keys=True), mimetype='application/json') 
Example 40
Project: python-flask-restful-api   Author: akashtalole   File: __init__.py    MIT License 5 votes vote down vote up
def internal_server_error(error):
    if current_app.config['PROPOGATE_ERROR'] is True:
        exc = JsonApiException({'pointer': ''}, str(error))
    else:
        exc = JsonApiException({'pointer': ''}, 'Unknown error')
    return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,
                         {'Content-Type': 'application/vnd.api+json'}) 
Example 41
Project: invenio-records-rest   Author: inveniosoftware   File: json.py    MIT License 5 votes vote down vote up
def serialize(self, pid, record, links_factory=None, **kwargs):
        """Serialize a single record and persistent identifier.

        :param pid: Persistent identifier instance.
        :param record: Record instance.
        :param links_factory: Factory function for record links.
        """
        return json.dumps(
            self.transform_record(pid, record, links_factory, **kwargs),
            **self._format_args()) 
Example 42
Project: flask-graphql-rest   Author: biosustain   File: utils.py    MIT License 5 votes vote down vote up
def open(self, *args, **kwargs):
        """
        Sends HTTP Authorization header with  the ``HTTP_AUTHORIZATION`` config value
        unless :param:`authorize` is ``False``.
        """
        headers = kwargs.pop('headers', [])

        if 'data' in kwargs and not isinstance(kwargs['data'], str):
            kwargs['data'] = json.dumps(kwargs['data'])
            kwargs['content_type'] = 'application/json'

        return super(ApiClient, self).open(*args, headers=headers, **kwargs) 
Example 43
Project: byceps   Author: byceps   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def health():
    """Return health status as JSON.

    Adheres to "Health Check Response Format for HTTP APIs"
    (draft-inadarei-api-health-check-03). See
    https://inadarei.github.io/rfc-healthcheck/#rfc.section.3
    for details.
    """
    rdbms_ok = _is_rdbms_ok()

    data = {
        'status': 'ok',
        'details': {
            'rdbms': [
                {
                    'status': 'ok' if rdbms_ok else 'fail',
                },
            ],
        },
    }

    json = dumps(data) + '\n'
    status_code = 503 if not rdbms_ok else 200

    return current_app.response_class(
        json, status=status_code, content_type='application/health+json'
    ) 
Example 44
Project: oa_qian   Author: sunqb   File: widgets.py    Apache License 2.0 5 votes vote down vote up
def recaptcha_html(self, query, options):
        html = current_app.config.get('RECAPTCHA_HTML', RECAPTCHA_HTML)
        server = current_app.config.get(
            'RECAPTCHA_API_SERVER', RECAPTCHA_API_SERVER
        )
        return Markup(html % dict(
            script_url='%schallenge?%s' % (server, query),
            frame_url='%snoscript?%s' % (server, query),
            options=json.dumps(options, cls=_JSONEncoder)
        )) 
Example 45
Project: PyChunkedGraph   Author: seung-lab   File: app_utils.py    Mozilla Public License 2.0 5 votes vote down vote up
def jsonify_with_kwargs(data, **kwargs):
    kwargs.setdefault("separators", (",", ":"))

    if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
        kwargs["indent"] = 2
        kwargs["separators"] = (", ", ": ")

    return current_app.response_class(
        json.dumps(data, **kwargs) + "\n", mimetype=current_app.config["JSONIFY_MIMETYPE"]
    ) 
Example 46
Project: MegaQC   Author: ewels   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def report_plot():
    # Get the fields from the add-new-filters form
    return_data = aggregate_new_parameters(current_user,[], False)
    sample_filters=order_sample_filters()
    return render_template(
        'public/report_plot.html',
        db = db,
        User = User,
        user_token = current_user.api_token,
        sample_filters = sample_filters,
        num_samples = return_data[0],
        report_fields_json = json.dumps(return_data[1]),
        sample_fields_json = json.dumps(return_data[2]),
        report_plot_types = return_data[3]
        ) 
Example 47
Project: InvenioRDM-at-NU   Author: galterlibrary   File: json.py    MIT License 5 votes vote down vote up
def serialize_search(self, pid_fetcher, search_result, links=None,
                         item_links_factory=None, **kwargs):
        """Serialize a search result.

        Overrides parent's serialize_search. This is done to format
        the nested aggregations per what the front-end expects.

        :param pid_fetcher: Persistent identifier fetcher.
        :param search_result: Elasticsearch search result.
        :param links: Dictionary of links to add to response.
        :param item_links_factory: Factory to create links to add to response.
        """
        hits_dict = {
            'hits': {
                'hits': [
                    self.transform_search_hit(
                        pid_fetcher(hit['_id'], hit['_source']),
                        hit,
                        links_factory=item_links_factory,
                        **kwargs
                    )
                    for hit in search_result['hits']['hits']
                ],
                'total': search_result['hits']['total']
            },
            'links': links or {},
            # This is the only new/different thing from parent
            'aggregations': self.transform_aggregation(
                search_result.get('aggregations', {})
            )
        }

        return json.dumps(hits_dict, **self._format_args()) 
Example 48
Project: sam-s-club-auctions   Author: sameer2800   File: app.py    Apache License 2.0 5 votes vote down vote up
def setKeys():
	if request.headers['Content-Type'] == 'application/json':		
		global api
		inputData = request.json
		consumer_key = inputData["consumer_key"]
		consumer_secret = inputData["consumer_secret"]
		access_token = inputData["access_token"]
		access_token_secret = inputData["access_token_secret"]	
		api = Authenticate_keys(consumer_key,consumer_secret,access_token,access_token_secret)
		data = {}
		data['status'] = 200
		json_data = json.dumps(data)
		return json_data 
Example 49
Project: sam-s-club-auctions   Author: sameer2800   File: app.py    Apache License 2.0 5 votes vote down vote up
def getList():
	if request.headers['Content-Type'] == 'application/json':		
		inputData = request.json
		auction_id = inputData["auction_id"]
		replies = fetch_replies_of_tweet(api,auction_id)
		data = {}
		data['replies'] = replies
		json_data = json.dumps(data)
		return json_data 
Example 50
Project: sam-s-club-auctions   Author: sameer2800   File: app.py    Apache License 2.0 5 votes vote down vote up
def createReply():
	if request.headers['Content-Type'] == 'application/json':		
		inputData = request.json
		tweet_id = inputData["tweet_id"]
		auction_id = inputData["auction_id"]
		bid_value = inputData["bid_value"]

		create_new_reply(api, tweet_id, auction_id, bid_value)
		data = {}
		data['status'] = 200
		json_data = json.dumps(data)
		return json_data 
Example 51
Project: sam-s-club-auctions   Author: sameer2800   File: app.py    Apache License 2.0 5 votes vote down vote up
def createWinnerTweet():
	if request.headers['Content-Type'] == 'application/json':		
		inputData = request.json
		auction_id = inputData["auction_id"]
		product_name = inputData["product_name"]
		image_url = inputData["image_url"]
		product_url = inputData["product_url"]
		winner_handle = inputData["winner_handle"]		
		winner_tweet(api, winner_handle, auction_id,image_url, product_url , product_name)	
		data = {}
		data['status'] = 200
		json_data = json.dumps(data)
		return json_data 
Example 52
Project: selene-backend   Author: MycroftAI   File: device.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_pairing_token(self, pairing_data):
        self.cache.set_with_expiration(
            key='pairing.token:' + pairing_data['token'],
            value=json.dumps(pairing_data),
            expiration=ONE_DAY
        ) 
Example 53
Project: selene-backend   Author: MycroftAI   File: add_account.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def call_add_account_endpoint(context):
    context.client.content_type = 'application/json'
    context.response = context.client.post(
        '/api/account',
        data=json.dumps(context.new_account_request),
        content_type='application/json'
    ) 
Example 54
Project: flask-rak   Author: Huong-nt   File: core.py    Apache License 2.0 5 votes vote down vote up
def dbgdump(obj, default=None, cls=None):
    if current_app.config.get('RAK_PRETTY_DEBUG_LOGS', False):
        indent = 2
    else:
        indent = None
    msg = json.dumps(obj, indent=indent, default=default, cls=cls)
    logger.debug(msg) 
Example 55
Project: hdxscraper-undp-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def post_data(self, data, table):
        # returns status_code 201
        url = base + table
        r = self.client.post(url, data=dumps(data), content_type=self.json)
        return r 
Example 56
Project: hdxscraper-undp-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def patch_data(self, data, table, id=None, query=None):
        # returns status_code 200 or 201
        if id:
            url = base + table + '/' + id
        else:
            url = base + table

        if query:
            r = self.client.patch(
                url, data=dumps(data), content_type=self.json, q=query)
        else:
            r = self.client.patch(url, data=dumps(data), content_type=self.json)

        return r 
Example 57
Project: GeoNature-citizen   Author: PnX-SI   File: routes.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_rewards(id):
    from gncitizen.utils.rewards import get_rewards, get_badges

    badges, rewards = get_badges(id), get_rewards(id)
    current_app.logger.debug("rewards: %s", json.dumps(rewards, indent=4))
    return (
        {
            "badges": badges,
            "rewards": rewards,
            "REWARDS": current_app.config["REWARDS"],
        },
        200,
    ) 
Example 58
Project: arch-security-tracker   Author: archlinux   File: util.py    MIT License 5 votes vote down vote up
def json_response(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        response = func(*args, **kwargs)
        code = 200
        if isinstance(response, tuple):
            response, code = response
        dump = json.dumps(response, indent=2, sort_keys=False)
        return dump, code, {'Content-Type': 'application/json; charset=utf-8'}
    return wrapped 
Example 59
Project: partycrasher   Author: naturalness   File: api_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def jsonify_list(seq):
    """
    Same as jsonify, but works on lists. Flask's JSONify doesn't support this
    because attackers can override Array's constructor to collect data when
    JSON is transferted as application/javascript.
    """
    # Coerce to list
    assert isinstance(seq, list)

    should_indent = not (request.headers.get('X-Requested-With', '') ==
                         'XMLHttpRequest')
    body = json.dumps(seq, indent=4 if should_indent else None)

    return make_response((body, None, {'Content-Type': 'application/json'})) 
Example 60
Project: partycrasher   Author: naturalness   File: service.py    GNU General Public License v3.0 5 votes vote down vote up
def jsonify_resource(resource):
    indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
            and not request.is_xhr:
        indent = 2
    return current_app.response_class(json.dumps(resource, indent=indent),
                                      mimetype='application/json') 
Example 61
Project: partycrasher   Author: naturalness   File: api_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def jsonify_list(seq):
    """
    Same as jsonify, but works on lists. Flask's JSONify doesn't support this
    because attackers can override Array's constructor to collect data when
    JSON is transferted as application/javascript.
    """
    # Coerce to list
    assert isinstance(seq, list)

    should_indent = not (request.headers.get('X-Requested-With', '') ==
                         'XMLHttpRequest')
    body = json.dumps(seq, indent=4 if should_indent else None)

    return make_response((body, None, {'Content-Type': 'application/json'})) 
Example 62
Project: partycrasher   Author: naturalness   File: service.py    GNU General Public License v3.0 5 votes vote down vote up
def jsonify_resource(resource):
    indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
            and not request.is_xhr:
        indent = 2
    return current_app.response_class(json.dumps(resource, indent=indent),
                                      mimetype='application/json') 
Example 63
Project: console   Author: amalgam8   File: app.py    Apache License 2.0 5 votes vote down vote up
def get_recipe_results():
    payload = request.get_json()
    #print json.dumps(payload, indent=2)
    args = settings
    #args.start_time = payload["start_time"]
    #args.header = payload["header"]
    #args.pattern = payload["pattern"]
    args.trace_log_value = payload["trace_log_value"]
    args.checks = payload["checks"]
    res = commands.validate_recipe(args)
    return jsonify(rules=res) 
Example 64
Project: XMorbid   Author: NMTech0x90   File: tag.py    GNU General Public License v3.0 5 votes vote down vote up
def dumps(self, value):
        """Tag the value and dump it to a compact JSON string."""
        return dumps(self.tag(value), separators=(',', ':')) 
Example 65
Project: FuzzFlow   Author: talos-vulndev   File: __init__.py    MIT License 5 votes vote down vote up
def upload_file():
    if 'file' not in request.files:
        return json.dumps({"err": "invalid request"}), 400

    u_file = request.files['file']
    if u_file.filename == '':
        return json.dumps({"err": "invalid request"}), 400

    path = os.path.join(config.UPLOAD_FOLDER, str(uuid.uuid4()))

    u_file.save(path)
    return json.dumps({"upload_path": path}), 200 
Example 66
Project: vibe   Author: 3ll3d00d   File: handler.py    MIT License 5 votes vote down vote up
def _doPut(self, url, data=None):
        formattedPayload = None if data is None else json.dumps(data, sort_keys=True)
        try:
            return self.httpclient.put(url, json=formattedPayload).status_code
        except Exception as e:
            self.logger.exception(e)
            return 500 
Example 67
Project: hawken-tracker   Author: ashfire908   File: __init__.py    MIT License 5 votes vote down vote up
def api_response(payload, status):
    return Response(response=json.dumps(payload), status=status, mimetype="application/json")

# Load submodules 
Example 68
Project: Humio_Webhook_Logger   Author: littl3field   File: App_Main.py    MIT License 5 votes vote down vote up
def get_payload():
    if (request.headers['content-type'] == 'application/json' and
            request.headers['token'] == 'ADD TOKEN'):
        log = json.dumps(request.json)
        with open('/home/humiologs.json', 'a') as f:
            json.dump(request.json, f)
            f.write("\n")
            return(log)
        f.close()
    else:
        return("Invalid Hash")

#Set logging on application route 
Example 69
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 5 votes vote down vote up
def submit_lifecycle_ignition(request_raw_query):
    """
    Lifecycle Ignition
    ---
    tags:
      - lifecycle
    responses:
      200:
        description: A JSON of the ignition status
    """
    try:
        machine_ignition = json.loads(request.get_data())
    except ValueError:
        app.logger.error("%s have incorrect content" % request.path)
        return jsonify({"message": "FlaskValueError"}), 406
    req = requests.get("%s/ignition?%s" % (EC.matchbox_uri, request_raw_query))
    try:
        matchbox_ignition = json.loads(req.content)
        req.close()
    except ValueError:
        app.logger.error("%s have incorrect matchbox return" % request.path)
        return jsonify({"message": "MatchboxValueError"}), 406

    @smartdb.cockroach_transaction
    def op(caller=request.url_rule):
        with SMART.new_session() as session:
            try:
                inject = crud.InjectLifecycle(session, request_raw_query=request_raw_query)
                if json.dumps(machine_ignition, sort_keys=True) == json.dumps(matchbox_ignition, sort_keys=True):
                    inject.refresh_lifecycle_ignition(True)
                    return jsonify({"message": "Up-to-date"}), 200
                else:
                    inject.refresh_lifecycle_ignition(False)
                    return jsonify({"message": "Outdated"}), 210
            except AttributeError:
                return jsonify({"message": "Unknown"}), 406

    return op(caller=request.url_rule) 
Example 70
Project: Blockly-rduino-communication   Author: technologiescollege   File: tag.py    GNU General Public License v3.0 5 votes vote down vote up
def dumps(self, value):
        """Tag the value and dump it to a compact JSON string."""
        return dumps(self.tag(value), separators=(',', ':')) 
Example 71
Project: tulo-chatbot   Author: usriva2405   File: flask_controller.py    MIT License 5 votes vote down vote up
def query():
    data = request.get_json()
    # fetch request objects
    inquiry = data['query']
    token = data['token']
    lang = data['lang']
    broker_id = data['broker_id']

    answer = chatService.predict_response(token, broker_id, lang, inquiry)

    logger.info('************************')
    logger.info('Prediction given by model')
    logger.info('************************')
    logger.info("answer : {0}".format(answer))
    logger.info('************************')

    # response = QueryResponse(answer)
    # print("****************************")
    # print("****************************")
    print(json.dumps(answer))
    # try:
    #     jsonStr = jsonify(response.toJSON())
    # except:
    #     logger.info("error ", sys.exc_info()[0])
    #     jsonStr = None

    return json.dumps(answer) 
Example 72
Project: tulo-chatbot   Author: usriva2405   File: flask_controller.py    MIT License 5 votes vote down vote up
def retrain():
    data = request.get_json()
    # fetch request objects
    token = data['token']
    lang = data['lang']
    broker_id = data['broker_id']

    logger.info("***************retraining started*******************")
    logger.info("token : {0}".format(token))
    logger.info("lang : {0}".format(lang))
    logger.info("broker_id : {0}".format(broker_id))

    answer = trainService.retrain(token, broker_id, lang)

    return json.dumps(answer) 
Example 73
Project: stop2.0-backend   Author: STOP2   File: stop.py    MIT License 5 votes vote down vote up
def digitransit_test():
    major_minor = [{"major":43118, "minor":56850}, {"major": 18105 , "minor":59204}]
    return json.dumps(digitransitAPIService.get_busses_with_beacon(major_minor))
    #return json.dumps(digitransitAPIService.fetch_single_trip("HSL:1055_20161107_Ti_2_1329"))
    #return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573)) 
Example 74
Project: LOST   Author: kylemh   File: api.py    MIT License 4 votes vote down vote up
def activate_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])

        # If http request is missing a parameter...
        if 'username' not in api_req or 'password' not in api_req or 'role' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameters'})
            return error_result
        else:
            username = api_req['username']
            password = api_req['password']
            role = api_req['role']

        # Handle errors within CLI arguments.
        if len(username) > 16 or len(password) > 16:
            error_result = json.dumps({'result': 'Error: Username or Password Too Long'})
            return error_result

        # All parameters are valid.
        if role == 'logofc':
            role = 2
        elif role == 'facofc':  # facofc
            role = 3
        else:
            error_result = json.dumps({'result': 'Error: Unsupported Role'})
            return error_result

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = helpers.db_query(matching_user, [username])

        # If user exists in database, activate user; otherwise, create and activate new user.
        if user_does_exist:
            activate_existing_user = ("UPDATE users SET password = %s, active = TRUE "
                                      "WHERE username = %s")
            helpers.db_change(activate_existing_user, [password, username])
        else:
            create_user = ("INSERT INTO users (user_pk, role_fk, username, password, active) "
                           "VALUES (DEFAULT, %s, %s, %s, TRUE)")
            helpers.db_change(create_user, [role, username, password])

        data = json.dumps({'result': 'OK'})
        return data 
Example 75
Project: LOST   Author: kylemh   File: api.py    MIT License 4 votes vote down vote up
def activate_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])

        # If http request is missing a parameter...
        if 'username' not in api_req or 'password' not in api_req or 'role' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameters'})
            return error_result
        else:
            username = api_req['username']
            password = api_req['password']
            role = api_req['role']

        # Handle errors within CLI arguments.
        if len(username) > 16:
            error_result = json.dumps({'result': 'Error: Username Too Long'})
            return error_result

        # All parameters are valid.
        if role == 'logofc':
            role = 2
        elif role == 'facofc':  # facofc
            role = 3
        else:
            error_result = json.dumps({'result': 'Error: Unsupported Role'})
            return error_result

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = db_query(matching_user, [username])

        # If user exists in database, activate user; otherwise, create and activate new user.
        if user_does_exist:
            activate_existing_user = ("UPDATE users SET password = %s, active = TRUE "
                                      "WHERE username = %s")
            db_change(activate_existing_user, [password, username])
        else:
            create_user = ("INSERT INTO users (user_pk, role_fk, username, password, active) "
                           "VALUES (DEFAULT, %s, %s, %s, TRUE)")
            db_change(create_user, [role, username, password])

        data = json.dumps({'result': 'OK'})
        return data 
Example 76
Project: jenca-authentication   Author: bimlauncher   File: storage.py    MIT License 4 votes vote down vote up
def users_route():
    """
    **POST**:

    Create a new user.

    :param email: The email address of the new user.
    :type email: string
    :param password_hash: A password hash to associate with the given ``email``
        address.
    :type password_hash: string
    :reqheader Content-Type: application/json
    :resheader Content-Type: application/json
    :resjson string email: The email address of the new user.
    :resjson string password_hash: The password hash of the new user.
    :status 200: A user with the given ``email`` and ``password_hash`` has been
        created.
    :status 409: There already exists a user with the given ``email``.

    **GET**:

    Get information about all users.

    :reqheader Content-Type: application/json
    :resheader Content-Type: application/json
    :resjsonarr string email: The email address of a user.
    :resjsonarr string password_hash: The password hash of a user.
    :status 200: Information about all users is returned.
    """

    if request.method == 'POST':
        return create_user()

    # It the method type is not POST it is GET.
    details = [
        {'email': user.email, 'password_hash': user.password_hash} for user
        in User.query.all()]

    return make_response(
        json.dumps(details),
        codes.OK,
        {'Content-Type': 'application/json'}) 
Example 77
Project: sequeval   Author: D2KLab   File: webapp.py    MIT License 4 votes vote down vote up
def run():
    _user_ratings = int(request.args.get('user-ratings'))
    _item_ratings = int(request.args.get('item-ratings'))
    _splitter = request.args.get('splitter')
    _ratio = float(request.args.get('ratio')) / 100
    _k = int(request.args.get('length'))

    loader = sequeval.UIRTLoader(user_ratings=_user_ratings, item_ratings=_item_ratings)
    ratings = loader.load('datasets/yes_reduced.csv')

    builder = sequeval.Builder('1000 s')
    sequences, items = builder.build(ratings)

    profiler = sequeval.Profiler(sequences)
    response = {'profiler': {'users': profiler.users(),
                             'items': profiler.items(),
                             'ratings': profiler.ratings(),
                             'sequences': profiler.sequences(),
                             'sparsity': parse(profiler.sparsity()),
                             'length': parse(profiler.sequence_length())}}

    if _splitter == 'random':
        splitter = sequeval.RandomSplitter(_ratio)
    else:
        splitter = sequeval.TimestampSplitter(_ratio)
    training_set, test_set = splitter.split(sequences)
    response['splitter'] = {'training': len(training_set),
                            'test': len(test_set)}

    evaluator = sequeval.Evaluator(training_set, test_set, items, _k)
    cosine = sequeval.CosineSimilarity(training_set, items)

    response['evaluator'] = []

    most_popular = baseline.MostPopularRecommender(training_set, items)
    response['evaluator'].append(evaluation(evaluator, most_popular, cosine))

    random = baseline.RandomRecommender(training_set, items)
    response['evaluator'].append(evaluation(evaluator, random, cosine))

    unigram = baseline.UnigramRecommender(training_set, items)
    response['evaluator'].append(evaluation(evaluator, unigram, cosine))

    bigram = baseline.BigramRecommender(training_set, items)
    response['evaluator'].append(evaluation(evaluator, bigram, cosine))

    return json.dumps(response) 
Example 78
Project: oa_qian   Author: sunqb   File: views.py    Apache License 2.0 4 votes vote down vote up
def jsonpify(*args, **kw):
    """Passes the specified arguments directly to :func:`jsonify` with a status
    code of 200, then wraps the response with the name of a JSON-P callback
    function specified as a query parameter called ``'callback'`` (or does
    nothing if no such callback function is specified in the request).

    If the keyword arguments include the string specified by :data:`_HEADERS`,
    its value must be a dictionary specifying headers to set before sending the
    JSONified response to the client. Headers on the response will be
    overwritten by headers specified in this dictionary.

    If the keyword arguments include the string specified by :data:`_STATUS`,
    its value must be an integer representing the status code of the response.
    Otherwise, the status code of the response will be :http:status:`200`.

    """
    # HACK In order to make the headers and status code available in the
    # content of the response, we need to send it from the view function to
    # this jsonpify function via its keyword arguments. This is a limitation of
    # the mimerender library: it has no way of making the headers and status
    # code known to the rendering functions.
    headers = kw.pop(_HEADERS, {})
    status_code = kw.pop(_STATUS, 200)
    response = jsonify(*args, **kw)
    callback = request.args.get('callback', False)
    if callback:
        # Reload the data from the constructed JSON string so we can wrap it in
        # a JSONP function.
        data = json.loads(response.data)
        # Force the 'Content-Type' header to be 'application/javascript'.
        #
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is valid
        # Javascript, but not valid JSON.
        headers['Content-Type'] = 'application/javascript'
        # Add the headers and status code as metadata to the JSONP response.
        meta = _headers_to_json(headers) if headers is not None else {}
        meta['status'] = status_code
        inner = json.dumps(dict(meta=meta, data=data))
        content = '{0}({1})'.format(callback, inner)
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is not valid JSON.
        mimetype = 'application/javascript'
        response = current_app.response_class(content, mimetype=mimetype)
    # Set the headers on the HTTP response as well.
    if headers:
        set_headers(response, headers)
    response.status_code = status_code
    return response 
Example 79
Project: xuemc   Author: skycucumber   File: views.py    GNU General Public License v2.0 4 votes vote down vote up
def jsonpify(*args, **kw):
    """Passes the specified arguments directly to :func:`jsonify` with a status
    code of 200, then wraps the response with the name of a JSON-P callback
    function specified as a query parameter called ``'callback'`` (or does
    nothing if no such callback function is specified in the request).

    If the keyword arguments include the string specified by :data:`_HEADERS`,
    its value must be a dictionary specifying headers to set before sending the
    JSONified response to the client. Headers on the response will be
    overwritten by headers specified in this dictionary.

    If the keyword arguments include the string specified by :data:`_STATUS`,
    its value must be an integer representing the status code of the response.
    Otherwise, the status code of the response will be :http:status:`200`.

    """
    # HACK In order to make the headers and status code available in the
    # content of the response, we need to send it from the view function to
    # this jsonpify function via its keyword arguments. This is a limitation of
    # the mimerender library: it has no way of making the headers and status
    # code known to the rendering functions.
    headers = kw.pop(_HEADERS, {})
    status_code = kw.pop(_STATUS, 200)
    response = jsonify(*args, **kw)
    callback = request.args.get('callback', False)
    if callback:
        # Reload the data from the constructed JSON string so we can wrap it in
        # a JSONP function.
        data = json.loads(response.data)
        # Force the 'Content-Type' header to be 'application/javascript'.
        #
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is valid
        # Javascript, but not valid JSON.
        headers['Content-Type'] = 'application/javascript'
        # Add the headers and status code as metadata to the JSONP response.
        meta = _headers_to_json(headers) if headers is not None else {}
        meta['status'] = status_code
        inner = json.dumps(dict(meta=meta, data=data))
        content = '{0}({1})'.format(callback, inner)
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is not valid JSON.
        mimetype = 'application/javascript'
        response = current_app.response_class(content, mimetype=mimetype)
    # Set the headers on the HTTP response as well.
    if headers:
        set_headers(response, headers)
    response.status_code = status_code
    return response 
Example 80
Project: Portfolio-compute   Author: IBM   File: run.py    Apache License 2.0 4 votes vote down vote up
def compute_unit_tests():
    '''
    Calculates analytics for a portfolio.
    Breaks into 500 instrument chunks to comply with container constraints.
    '''
    if request.method == 'POST':
        portfolios = []
        data = json.loads(request.data)
        portfolios.append(data["portfolio"])

    #Stopwatch
    start_time = datetime.datetime.now()
    if data:
        analytics = data["analytics"]
    else:
        analytics = ['THEO/Price','THEO/Value']
    results = []

    for p in portfolios:
        portfolio_start = datetime.datetime.now()
        holdings = investmentportfolio.Get_Portfolio_Holdings(p,False)['holdings']
        #Since the payload is too large, odds are there are 500-instrument chunks added to the portfolio.
        for ph in range(0,len(holdings)):
            instruments = [row['instrumentId'] for row in holdings[ph]['holdings']]
            print("Processing " + str(p) + " portfolio segment #"+str(ph) +".")
            #send 500 IDs at a time to Instrument Analytics Service:
            #for i in instruments...
            for i in range(0,len(instruments),500):
                ids = instruments[i:i+500]
                ia = instrumentanalytics.Compute_InstrumentAnalytics(ids,analytics)
                #for j in results...
                if 'error' not in ia:
                    for j in ia:
                        r = {
                            "portfolio":p,
                            "id":j['instrument']}
                        for a in analytics:
                            r[a] = j['values'][0][a]
                        r["date"] = j['values'][0]['date']
                        h = [row for row in holdings[0]['holdings'] if j['instrument']==row['instrumentId']][0]
                        for key,value in h.items():
                            if key not in ['instrumentId']:
                                r[key] = value
                        results.append(r)
                #Debug
                if i+500<len(instruments):
                    l = i+500
                else:
                    l = len(instruments)
                print("Processed securities " + str(i) + " through " + str(l) + ". Time elapsed on this portfolio: " + str(datetime.datetime.now() - portfolio_start))

    print("Unit testing completed. Total time elapsed: " + str(datetime.datetime.now() - start_time))
    return Response(json.dumps(results), mimetype='application/json')