コード例 #1
0
ファイル: schema.py プロジェクト: jroimartin/lemur
        def decorated_function(*args, **kwargs):
            if input_schema:
                if request.get_json():
                    request_data = request.get_json()
                else:
                    request_data = request.args

                data, errors = input_schema.load(request_data)

                if errors:
                    return wrap_errors(errors), 400

                kwargs['data'] = data

            try:
                resp = f(*args, **kwargs)
            except Exception as e:
                current_app.logger.exception(e)
                return dict(message=e.message), 500

            if isinstance(resp, tuple):
                return resp[0], resp[1]

            if not resp:
                return dict(message="No data found"), 404

            if output_schema:
                data = output_schema.dump(resp)
                return data.data, 200
            return resp, 200
コード例 #2
0
ファイル: push.py プロジェクト: Muxi-Studio/restccnu
def push_register():
    """
    :function: push_register
    :args: none
    :rv: success message

    redis(6384): string
        key: "ids"
        vlaue: "['id1', 'id2']"

    注册ios设备的unique_id
    """
    if request.method == 'POST':
        unique_id = request.get_json().get('unique_id')
        sid = request.get_json().get('sid')  # 学号
        # 将unique_id写入数据库
        if not rds.get('ids'):
            rds.set('ids', "[]")
            rds.save()
        ids = ast.literal_eval(rds.get('ids'))
        if unique_id and (unique_id not in ids):
            ids.append(unique_id)
        if sid:
            rds.hset('idsids', unique_id, sid)
        # db commit
        rds.set('ids', ids)
        rds.save()
        return jsonify({
            'message': 'add new unique_id'
        }), 201
コード例 #3
0
def getNER():
    if not request.get_json(force=True) or not 'text' in request.get_json(force=True):
        print 'aborting'
        abort(400)


    # istr = request.json['text']
    istr = request.get_json(force=True)['text'] 
    n = int(request.get_json(force=True)['max_n'] )
    # remove all nonAsciiCharacters
    istr = removeNonAscii(istr)

    inclusion_list = DB.getInclusionList()
    exclusion_list = DB.getExclusionList()

    istr = removeNonAscii(istr)

    NER_results = NER.findNamedEntities(istr, inclusion_list)

    keywords = NER_results[0:n]

    # omit repeats and return lowercase
    keywords = sorted(list(set(i.lower() for i in keywords)))
    keywords = NER.excludeKeywords(exclusion_list, keywords)



    return jsonify({'keywords': keywords}), 201
コード例 #4
0
def offer():
  print("Received resource offer:")
  print(json.dumps(request.get_json(), sort_keys=True, indent=2, separators=(',', ': ')))

  REQUIRED_MEM = 500
  REQUIRED_CPU = 0.5

  tasks_to_run = []

  info = request.get_json()

  if info["resources"]["cpus"] >= REQUIRED_CPU \
     and info["resources"]["mem"] >= REQUIRED_MEM:

    tasks_to_run.append(
      {
        "id": "my_job_" + str(random.randint(0, 1000)),
        "cmd": "pwd && /bin/sleep " + str(random.randint(10, 60)),
        "resources": {
          "cpus": REQUIRED_CPU,
          "mem": REQUIRED_MEM
        }
      }
    )

  print("Responding with the following tasks:")
  print(json.dumps(tasks_to_run, sort_keys=True, indent=2, separators=(',', ': ')))
  return Response(json.dumps(tasks_to_run),  mimetype='application/json')
コード例 #5
0
ファイル: app.py プロジェクト: optixx/userlike-chatbot
def get_state():
    try:
        state = request.get_json().get("context").get("state")
        klass = globals().get("State%s" % state.capitalize())
        return klass(request.get_json().get("input"))
    except:
        return StateStart()
コード例 #6
0
ファイル: app.py プロジェクト: AiWuxt/datamining
def city():
    req = request.get_json() if request.get_json() else {}
    gender = req['gender'] if 'gender' in req.keys() else ''
    region = req['region'] if 'region' in req.keys() else ''
    data = conn.get_cities_rate(gender=gender, region=region)
    print(data)
    return json.dumps(data)
コード例 #7
0
ファイル: web.py プロジェクト: hirogwa/highland
def audio():
    if 'POST' == request.method:
        file_name, duration, length, file_type = _get_args(
            request.get_json(), 'filename', 'duration', 'length',
            'filetype')
        audio = audio_operation.create(
            auth.authenticated_user.id, file_name, duration, length,
            file_type)
        return jsonify(audio=audio, result='success'), 201

    if 'GET' == request.method:
        args = request.args
        unused_only = args.get('unused_only') == 'True'
        whitelisted_id = args.get('whitelisted_id')
        user = auth.authenticated_user
        audios = audio_operation.load(
            user.id, unused_only,
            int(whitelisted_id) if whitelisted_id else None)

        return jsonify(audios=audios, result='success')

    if 'DELETE' == request.method:
        args = request.get_json()
        audio_operation.delete(auth.authenticated_user.id, args.get('ids'))
        return jsonify(result='success')
コード例 #8
0
ファイル: routes.py プロジェクト: EricSchles/dotify
def get_recommended_songs():
    country_ids = request.get_json()['country_ids']
    operator_ids = request.get_json()['operator_ids']
    country_vector_objects = session.query(CountryVector).filter(CountryVector.country_id.in_(country_ids)).all()
    operator_objects = session.query(Operator).filter(Operator.id.in_(operator_ids)).all()
    recommended_songs = [{'artist': artist, 'title': title, 'url': url} for title, artist, url in RecommendedSongGenerator(country_vector_objects, operator_objects)]
    return jsonify({'songs': recommended_songs}), 200
コード例 #9
0
ファイル: app.py プロジェクト: wangpin34/learn-python
def saveConf():
    print "save conf..."
    print request.get_json(force=False, silent=False, cache=True)
    mgmtportal = request.args.get("mgmtportal", "fk")
    # mgmtportal = request.form['mgmtportal']
    # res = {'mgmtportal':mgmtportal}
    return jsonify({"resultCode": 200, "resultMessage": "OK", "result": mgmtportal})
コード例 #10
0
ファイル: signup.py プロジェクト: Muxi-X/auth_microservice
def signup():
    """用户注册"""
    un = request.get_json().get("username")
    email = request.get_json().get("email")
    password = request.get_json().get("password")

    if User.query.filter_by(username=un).first() is not None:
        return jsonify ({}), 400
    if User.query.filter_by(email=email).first() is not None:
        return jsonify ({}), 400
    if un is None or email is None or password is None:
        return jsonify ({}), 400

    user = User(
        username = un,
        email = email,
        password = base64.b64encode(password),
        avatar_url = "http://7xrvvt.com1.z0.glb.clouddn.com/shakedog.gif",
        role_id = 3
        )

    db.session.add(user)
    db.session.commit()

    return jsonify({
        "created": user.id
        }), 200
コード例 #11
0
ファイル: controllers.py プロジェクト: Lowess/spiderami
def latest_ami(is_lts=None):
  ami_collection = crawl()
  
  # Filter results
  filters = dict()
  if request.method == 'POST':
      request.get_json()
  else:
    filters = request.args.to_dict()
    if 'pretty' in filters.keys():
      del filters['pretty']

  # Override parameters to make sure it matches latest critria
  filters['version'] = ami_collection.latest_version(is_lts=is_lts)
  if is_lts:
    filters['is_lts'] = is_lts
  
  filtered_amis = ami_collection.find(**filters)
  
  # Sort the result
  filtered_amis.sort_by(key="version", reverse=True)

  # Return a Json response
  json_res = json.loads(filtered_amis.to_json())
  json_res['hits'] = len(filtered_amis)
  return jsonify(json_res)
コード例 #12
0
def remove_collection():
    '''

    This router function removes a collection, with respect to a database type.

    @collection, indicates a nosql implementation
    @entity, indicates a sql database

    '''

    if request.method == 'POST':
        # local variables
        response = None
        entity = Entity()
        collection = Collection()

        # programmatic-interface
        if request.get_json():
            r = request.get_json()
            uid = r['uid']
            type = r['type']
            cname = r['collection']

            if (cname and type == 'collection'):
                payload = {'properties.uid': uid}
                response = collection.query(cname, 'drop_collection', payload)

            elif (type == 'entity'):
                response = entity.remove_entity(uid, cname)

        # lastrowid returned must be greater than 0
        if response and response['result']:
            return json.dumps({'response': response['result']})
        else:
            return json.dumps({'response': response})
コード例 #13
0
def document_count():
    '''

    This router function retrieves the number of documents in a specified
    collection.

    '''

    if request.method == 'POST':
        # local variables
        count = None
        collection = Collection()

        # programmatic-interface
        if request.get_json():
            r = request.get_json()
            cname = r['collection']
            count = collection.query(cname, 'count_documents')

        if (
            count and
            count['status'] and
            isinstance(count['result'], (int, long))
        ):
            return json.dumps({'count': count['result']})
        else:
            return json.dumps({'count': -1})
コード例 #14
0
ファイル: comment.py プロジェクト: rmoorman/kuulemma
def update(hearing_id, comment_id):
    if not (
        current_user.is_authenticated() and
        (current_user.is_official or current_user.is_admin)
    ):
        abort(401)

    Hearing.query.get_or_404(hearing_id)
    comment = Comment.query.get_or_404(comment_id)

    if not request.get_json() or is_spam(request.get_json()):
        abort(400)

    schema = CommentSchema(
        only=('title', 'body', 'username', 'is_hidden')
    )
    data, errors = schema.load(request.get_json())

    if errors:
        return jsonify({'error': errors}), 400

    comment.title = data['title']
    comment.body = data['body']
    comment.username = data['username']
    comment.is_hidden = data['is_hidden']
    comment.updated_at = datetime.utcnow()
    db.session.commit()

    serialized = CommentSchema(
        comment,
        exclude=('object_type', 'object_id')
    )

    return jsonify({'comment': serialized.data}), 200
コード例 #15
0
ファイル: config.py プロジェクト: JanVan01/gwot-physical
 def subscription(self, id):
     if (request.method == 'DELETE'):
         subscription = Subscribers().get(id)
         if subscription is None:
             return self.get_view().bad_request('Subscription does not exist')
         if subscription.delete():
             return self.get_view().success()
         else:
             return self.get_view().error()
     elif (request.method == 'PUT'):
         input = request.get_json()
         if(input is None):
             return self.get_view().bad_request('expected json')
         if('id' in input):
             try:
                 subscription = Subscribers().get(int(input['id']))
                 if subscription is None:
                     return self.get_view().bad_request('The subscription you are trying to update does not exist try to create it instead')
                 notification = Notifiers().get(int(input['notifier']))
                 if notification is None:
                     return self.get_view().bad_request('The notifier of your subscription does not exist')
                 if 'notifier' in input:
                     subscription.set_notifier(int(input['notifier']))
                 if 'sensor' in input:
                     subscription.set_sensor(int(input['sensor']))
                 if 'settings' in input:
                     if not self.__validate_subscription_settings(notification, input['settings']):
                         return self.get_view().bad_request('Settings not in the right format')
                     else:
                         subscription.set_settings(input['settings'])
                 if not subscription.update():
                     return self.get_view().bad_request('The Subscription you are trying to update does not exist try to create it instead')
             except ValueError:
                 return self.get_view().bad_request('Input not in the right format')
         else:
             return self.get_view().bad_request('Not all necessary field set')
         return self.get_view().success()
     elif (request.method == 'POST'):
         input = request.get_json()
         if(input is None):
             return self.get_view().bad_request('Expected json')
         if ('notifier' in input and 'sensor' in input and 'settings' in input):
             subscription = Subscribers().create()
             try:
                 notification = Notifiers().get(int(input['notifier']))
                 if notification is None:
                     return self.get_view().bad_request('The notifier of your subscription does not exist')
                 subscription.set_notifier(int(input['notifier']))
                 subscription.set_sensor(int(input['sensor']))
                 if not self.__validate_subscription_settings(notification, input['settings']):
                     return self.get_view().bad_request('Settings not in the right format')
                 else:
                     subscription.set_settings(input['settings'])
                 if not subscription.create():
                     return self.get_view().bad_request('The subscription could not be created')
             except ValueError:
                 return self.get_view().bad_request('input not in the right format')
         else:
             return self.get_view().bad_request('not all necessary field set')
         return self.get_view().success()
コード例 #16
0
ファイル: main.py プロジェクト: Ironarcher/casso-backend
def registerDevice():
	#Arguments are phone-id, email, phone number, security questions (4)
	if not request.get_json(force=True, silent=True):
		abort(400, "Request in the wrong format")
	req = request.get_json(force=True)
	if not 'phone-id' in req:
		abort(400, "Phone ID missing")
	if not 'emailaddress' in req:
		abort(400, "Email Address missing")
	if not 'phonenumber' in req:
		abort(400, "Phone number missing")
	if not 'secq1' in req or not 'seca1' in req or not 'secq2' in req or not 'seca2' in req or not 'secq3' in req or not 'seca3' in req or not 'secq4' in req or not 'seca4' in req:
		abort(400, "Security questions incomplete or missing")

	#Get the user in question from the secret phone key
	user_id = getUserFromPhone(req['emailaddress'], req['phonenumber'])
	secretkey = randKey(40)

	#Add security questons and phone-id to user profile
	cursor = db.cursor()
	sql = "INSERT INTO devices (secq1, secq2, secq3, secq4, seca1, seca2, seca3, seca4, phone_id, secretphonekey, user_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
	cursor.execute(sql, (req['secq1'], req['secq2'], req['secq3'], req['secq4'], req['seca1'], req['seca2'], req['seca3'], req['seca4'], req['phone-id'],
		secretkey, user_id))
	db.commit()

	sql = "SELECT url from websites WHERE pid=(SELECT website_id from users WHERE pid=%s)"
	cursor.execute(sql, (user_id,))
	if cursor.rowcount > 0:
		url = cursor.fetchone()[0]
	else:
		url = "unknown"
	cursor.close()
	return jsonify({"status":"success", "user_id":user_id, "secretphonekey":secretkey, "url":url})
コード例 #17
0
ファイル: form.py プロジェクト: KattMingMing/caravel
    def __init__(self, formdata=_Auto, obj=None, prefix='', csrf_context=None,
                 secret_key=None, csrf_enabled=None, **kwargs):

        if csrf_enabled is None:
            csrf_enabled = current_app.config.get('WTF_CSRF_ENABLED', True)

        self.csrf_enabled = csrf_enabled

        if formdata is _Auto:
            if self.is_submitted():
                formdata = request.form
                if request.files:
                    formdata = formdata.copy()
                    formdata.update(request.files)
                elif request.get_json():
                    formdata = werkzeug.datastructures.MultiDict(request.get_json())
            else:
                formdata = None

        if self.csrf_enabled:
            if csrf_context is None:
                csrf_context = session
            if secret_key is None:
                # It wasn't passed in, check if the class has a SECRET_KEY
                secret_key = getattr(self, "SECRET_KEY", None)

            self.SECRET_KEY = secret_key
        else:
            csrf_context = {}
            self.SECRET_KEY = ''
        super(FlaskForm, self).__init__(
            formdata, obj, prefix,
            csrf_context=csrf_context,
            **kwargs
        )
コード例 #18
0
ファイル: manager.py プロジェクト: fibomat/itxia-docker
def manager_login():
    username = request.get_json().get('username')
    encryption_str = request.get_json().get('encryption_str')
    random_str = request.get_json().get('random_str')
    time_stamp = request.get_json().get('time_stamp')
    manager = Manager.query.filter_by(username=username).first()

    if not username:
        return jsonify({'code': 0, 'message': 'No Manager Exist'})

    password_in_sql = manager.password

    s = hashlib.sha256()
    s.update(password_in_sql)
    s.update(random_str)
    s.update(time_stamp)
    server_encryption_str = s.hexdigest()

    if password_in_sql != encryption_str:#server_encryption_str != encryption_str:
        return jsonify({'code': 0, 'message': 'Wrong Password'})

    m = hashlib.md5()
    m.update(username)
    m.update(manager.password)
    m.update(str(int(time.time())))
    token = m.hexdigest()

    pipeline = redis.pipeline()
    pipeline.hmset('manager:%s' % manager.username, {'token': token, 'email': manager.email, 'app_online': 1})
    pipeline.set('token:%s' % token, manager.username)
    pipeline.expire('token:%s' % token, 3600*24*30)
    pipeline.execute()

    return jsonify({'code': 1, 'message': 'Successful Log In', 'email': manager.email, 'token': token})
コード例 #19
0
ファイル: api.py プロジェクト: GTxx/youjiao
def favor():
    # validate
    schema = FavorSchema()
    # import ipdb; ipdb.set_trace()
    # TODO: supprot json and form input, or just support json
    # if request.content_type == 'application/json':
    #    get data from request.json
    # if request.content_type == 'form...'
    #   get data from form

    # import ipdb; ipdb.set_trace()
    json_data = request.get_json()
    json_data.update({'user_id': current_user.id})
    data, error = schema.load(request.get_json())

    # data, error = schema.load({'password': '******'})
    if error:
        return jsonify(error), 400
    from sqlalchemy import exists, and_
    from youjiao.extensions import db
    obj_id = data.get('obj_id')
    obj_type = data.get('obj_type')
    ret = db.session.query(exists().where(
        and_(Favor.obj_id==obj_id,
             Favor.obj_type==obj_type,
             Favor.user_id==current_user.id))).scalar()
    if not ret:
        favor = Favor(**data)
        favor.save()
    return jsonify(data), 201
コード例 #20
0
def add_usuarios():
    u = UsuariosModel()
    print request.get_json()
    u.nome = request.get_json().get("nome")
    u.email = request.get_json().get("email")
    u.save()
    return jsonify({"message":"Usuario cadastrado com sucesso!"})
コード例 #21
0
ファイル: app.py プロジェクト: phone/ite
def open():
    cwd = request.get_json()['cwd']
    cmd = request.get_json()['cmd']
    ret, cwd, type = pp.pp_open(cmd, cwd)
    return jsonify({'output':unicode(ret),
                    'cwd':unicode(cwd),
                    'type':type})
コード例 #22
0
def getTFIDF():
    if not request.get_json(force=True) or not 'text' in request.get_json(force=True):
        print 'aborting'
        abort(400)


    # istr = request.json['text']
    istr = request.get_json(force=True)['text'] 
    n = int(request.get_json(force=True)['max_n'] )
    # remove all nonAsciiCharacters
    istr = removeNonAscii(istr)

    inclusion_list = DB.getInclusionList()
    exclusion_list = DB.getExclusionList()

    istr = removeNonAscii(istr)

    TFIDF_results = TFIDF.findTFIDFkeywords(istr)

    keywords = TFIDF_results[0:n]


    keywords = NER.excludeKeywords(exclusion_list, keywords)



    return jsonify({'keywords': keywords}), 201
コード例 #23
0
ファイル: feedback.py プロジェクト: City-of-Helsinki/kuulemma
def create():
    if not request.get_json():
        return jsonify({'error': 'Data should be in json format'}), 400

    if is_spam(request.get_json()):
        abort(400)

    content = request.get_json().get('content', '')
    if not content:
        return jsonify({'error': 'There was no content'}), 400
    feedback = Feedback(content=content)
    db.session.add(feedback)
    db.session.commit()

    message = Message(
        sender='*****@*****.**',
        recipients=FEEDBACK_RECIPIENTS,
        charset='utf8',
        subject='Kerrokantasi palaute',
        body=feedback.content
    )
    mail.send(message)

    return jsonify({
        'feedback': {
            'id': feedback.id,
            'content': feedback.content
        }
    }), 201
コード例 #24
0
ファイル: bot.py プロジェクト: ChameleonStudio/coolbot
def hook():
    chat_id = request.get_json()["message"]["chat"]["id"]
    text = request.get_json()["message"].get("text")
    location = request.get_json()["message"].get("location")

    if text:
        command, *args = text.split()

        if command == "/add":
            db.products.insert({"products": args})
            send(chat_id, "Products added.")

        if command == "/get":
            answer = "\n".join(
                map(str, db.products.find())
            )
            send(chat_id, answer)

        if command == "map":
            url = map(50.4116, 30.5284588, 14, 300, markers=[
                Marker("C", 50.4116, 30.5284588),
                Marker("A", 50.4117, 30.5284688, "green"),
            ])
            bot.sendPhoto(chat_id, url)

    if location:
        send(chat_id, "{}, {}".format(location["longitude"], location["latitude"]))
    return "OK"
コード例 #25
0
ファイル: server.py プロジェクト: dacut/dist.kanga.org
    def validate_message(self):
        """
        Verify the message signature.  We use the AWS Sigv4 algorithm here.
        """

        # Refuse to verify requests larger than the maximum we're willing
        # to handle.
        body = request.stream.read(self.max_request_size + 1)
        if len(body) > self.max_request_size:
            abort(BAD_REQUEST)

        # Cache the body so we can decode it later on.
        request._cached_data = body

        # Verify the signature.
        verifier = AWSSigV4Verifier(
            request.method, request.path, request.query_string,
            request.headers, body, self.region, self.service, self.keymap)

        try:
            verifier.verify()
        except InvalidSignatureError:
            from traceback import print_exc
            print_exc()
            abort(UNAUTHORIZED)

        # We only accept JSON; force it to be parsed now.
        try:
            request.get_json()
        except:
            self.app.logger.warning("No JSON data available", exc_info=True)
            raise

        return
コード例 #26
0
ファイル: ns_api.py プロジェクト: askagirl/sync-engine
def draft_update_api(public_id):
    data = request.get_json(force=True)
    original_draft = get_draft(public_id, data.get('version'), g.namespace.id,
                               g.db_session)

    # TODO(emfree): what if you try to update a draft on a *thread* that's been
    # deleted?

    data = request.get_json(force=True)

    to = get_recipients(data.get('to'), 'to')
    cc = get_recipients(data.get('cc'), 'cc')
    bcc = get_recipients(data.get('bcc'), 'bcc')
    from_addr = get_recipients(data.get('from_addr'), 'from_addr')
    reply_to = get_recipients(data.get('reply_to'), 'reply_to')

    if from_addr and len(from_addr) > 1:
        raise InputError("from_addr field can have at most one item")
    if reply_to and len(reply_to) > 1:
        raise InputError("reply_to field can have at most one item")

    subject = data.get('subject')
    body = data.get('body')
    files = get_attachments(data.get('file_ids'), g.namespace.id, g.db_session)

    draft = update_draft(g.db_session, g.namespace.account, original_draft,
                         to, subject, body, files, cc, bcc, from_addr,
                         reply_to)
    return g.encoder.jsonify(draft)
コード例 #27
0
ファイル: workspace.py プロジェクト: m038/superdesk
 def is_authorized(self, **kwargs):
     if kwargs.get("_id"):
         data = self.find_one(req=None, _id=kwargs.get("_id")) or request.get_json()
     else:
         data = request.get_json()
     # TODO(petr): use privileges to test who can save desk/role dashboard
     return "user" not in data or str(data["user"]) == str(kwargs["user_id"])
コード例 #28
0
ファイル: rz_api_rest.py プロジェクト: shlomif/rhizi
    def sanitize_input(req):
        rzdoc_name = request.get_json().get('rzdoc_name')
        topo_diff_dict = request.get_json()['topo_diff']
        topo_diff = Topo_Diff.from_json_dict(topo_diff_dict)

        sanitize_input__topo_diff(topo_diff)
        return rzdoc_name, topo_diff
コード例 #29
0
ファイル: ns_api.py プロジェクト: apolmig/inbox
def draft_update_api(public_id):
    data = request.get_json(force=True)
    original_draft = get_draft(public_id, data.get('version'), g.namespace.id,
                               g.db_session)

    # TODO(emfree): what if you try to update a draft on a *thread* that's been
    # deleted?

    data = request.get_json(force=True)

    to = get_recipients(data.get('to'), 'to')
    cc = get_recipients(data.get('cc'), 'cc')
    bcc = get_recipients(data.get('bcc'), 'bcc')
    subject = data.get('subject')
    body = data.get('body')
    tags = get_tags(data.get('tags'), g.namespace.id, g.db_session)
    files = get_attachments(data.get('file_ids'), g.namespace.id, g.db_session)

    try:
        draft = sendmail.update_draft(g.db_session, g.namespace.account,
                                      original_draft, to, subject, body,
                                      files, cc, bcc, tags)
    except ActionError as e:
        return err(e.error, str(e))

    return g.encoder.jsonify(draft)
コード例 #30
0
ファイル: views.py プロジェクト: cnssnewscenter/CNSS_Times
def posts(pid):
    if pid is None:
        if request.method == "GET":
            page = int(request.args.get("page", 1))
            return jsonify(err=0, data=[i.to_dict() for i in model.Post.select().where(model.Post.deleted == False).order_by(model.Post.published.desc()).paginate(page, 10)])
        elif request.method == "PUT":
            try:
                data = request.get_json()
                now = datetime.now()
                date = parse(data['published']).replace(tzinfo=None)
                if date.hour == 16:
                    date += timedelta(hours=8)
                model.Post.create(
                    title=data['title'],
                    content=data["content"],
                    header=data['header'],
                    author=data['author'],
                    created=now,
                    creator=g.user.username,
                    other={},
                    published=date,
                    operation_history=["created at {} by {}".format(now, g.user.username)],
                    status="toPublish"
                )
            except IndexError:
                abort(400)
            return jsonify(err=0, msg="新建成功")
    else:
        pid = int(pid)
        post = model.Post.try_get(id=pid)
        if post:
            if request.method == "GET":
                return jsonify(err=0, data=post.to_dict())
            elif request.method == "DELETE":
                post.deleted = True
                post.operation_history.append("deleted at {} by {}".format(datetime.now(), g.user.username))
                post.save()
                return jsonify(err=0, msg="已经删除到回收站")
            elif request.method == "POST":
                data = request.get_json()
                post.title = data['title']
                post.content = data['content']
                post.header = data['header']
                post.author = data["author"]
                post.other = data['other']
                date = parse(data['published']).replace(tzinfo=None)
                print(date)
                if date.hour == 16:
                    date += timedelta(hours=8)
                print(date)
                post.published = date
                post.operation_history.append("modified at {} by {}".format(datetime.now(), g.user.username))
                status = data.get('status')
                post.deleted = False
                if status and post.status != status:
                    post.status = status
                    post.operation_history.append("set as {} at {} by {}".format(status, datetime.now(), g.user.username))
                post.save()
                return jsonify(err=0, msg="修改成功")
        abort(404)
コード例 #31
0
ファイル: server.py プロジェクト: JanBartoszek/API-WARS
def vote():
    vote_input = request.get_json()
    logic.vote(vote_input)
    return json.dumps(vote_input['planet_name'])
コード例 #32
0
ファイル: server.py プロジェクト: JanBartoszek/API-WARS
def register_new_user():
    register_input = request.get_json()
    if logic.check_if_user_in_database(register_input) == True:
        return app.response_class(json.dumps(False), content_type='application/json')
    logic.register_new_user(register_input)
    return app.response_class(json.dumps(True), content_type='application/json')
コード例 #33
0
 def post(self):
     return self.get_request_handler(request.headers).add_new_provider(
         request.get_json())
コード例 #34
0
def returnData():
    posted_data = request.get_json()
    name = posted_data['name']
    return jsonify(" JSON Of fields " + name + "!!!")
コード例 #35
0
 def put(self, id):
     body = request.get_json()
     print(body)
     Todo.objects.get(id=id).update(**body)
     return {'id': str(id)}, 200
コード例 #36
0
ファイル: retrieve.py プロジェクト: jisung594/tracer-be
def get_info():
    if request.method == 'POST':
        req_obj = request.get_json()
        ticker = req_obj['symbol']

        return requests.get('https://finnhub.io/api/v1/stock/profile2?symbol=' + ticker + '&token=' + api_key).content
コード例 #37
0
 def inactivate_equipments(vessel_code):
     try:
         data = request.get_json()
         return jsonify(equipment_service.inactivate_equipments(vessel_code, data))
     except ResourceNotFound as e:
         return Response(e.message, HTTPStatus.NOT_FOUND)
コード例 #38
0
def edit(project, issue):
    """Edits an issue.

    Edits an issue's title and description. If the project's status is In Progress,
    edits the priority and assignee too.

    Produces:
        application/json
        text/html

    Args:
        project:
            in: edit_issue_permission_required() decorator
            type: Project
            description: A Project object whose id is the same as the id in the path.
        issue:
            in: edit_issue_permission_required() decorator
            type: Issue
            description: An Issue object whose id is the same as the id in the path.
        title:
            in: json
            type: string
            description: The issue's new title.
        description:
            in: json
            type: string
            description: The issue's new description.
        priority:
            in: json
            type: String
            description: The priority level of the issue.
        assignee_id:
            in: json
            type: String
            description: The assignee's id.


    Responses:
        200:
            description: Edit successfully.
        400:
            description: Bad request.
        403:
            description: Forbidden.
        404:
            description: Project or issue does not exist.
        422:
            description: Unprocessable.
    """

    body = request.get_json()
    title = body.get('title')
    description = body.get('description')
    if None in (title, description):
        abort(400)

    if issue.status == 'In Progress':
        priority = body.get('priority')
        assignee_id = body.get('assignee_id')
        if None in (priority, assignee_id):
            abort(400)

        new_assignee = edit_validation(issue, title, description, project,
                                       priority, assignee_id)
        issue.priority = priority
        if issue.assignee != new_assignee:
            if issue.assignee != current_user:
                issue.assignee.add_notification(
                    'remove assignee',
                    {
                        'avatar': current_user.avatar(),
                        'fullname': current_user.fullname(),
                        'issueTitle': issue.title,
                    },
                )
            if new_assignee != current_user:
                new_assignee.add_notification(
                    'assign issue',
                    {
                        'avatar': current_user.avatar(),
                        'fullname': current_user.fullname(),
                        'projectId': project.id,
                    },
                    issue.id,
                )
            issue.assignee_id = assignee_id
    else:
        edit_validation(issue, title, description)

    issue.title = title
    issue.description = description
    db.session.commit()

    return {'success': True}
コード例 #39
0
def webhook_post():
    global qlist, risk, raw_companies, phone_number
    data = request.get_json()
    q_type = list(data.get('queryResult').get("parameters").keys())[0]
    response = data.get('queryResult').get('queryText')
    print("Question types %s : %s" % (q_type, response))
    if q_type == "Tolerance":
        risk = response
    elif q_type == "any":
        #raw_companies = data.get('queryResult').get("parameters").values()[0]
        raw_companies = response
    elif q_type == "Response":
        response = data.get('queryResult').get("parameters").get("Response")[0]
        qlist.append(response)
    elif q_type == "Reset":
        reset()
    elif q_type == "PhoneNumber":
        print("pre append", response)
        response = response + ","
        print("post append", response)
        phone_number = "".join([
            s for s in re.split(';|,|\*|\n|\.|,|!|@|#|$|%|\^|&|\(|\)|-|_| ',
                                response) if len(s) > 0
        ])
    else:
        pass
    print("Q type", q_type)
    print("Q list", qlist)
    print("Risk factor", risk)
    print("Phone number", phone_number)
    print("Raw Companies", raw_companies)

    # check if we can calc risky
    if (len(qlist) == 13 and risk == None):
        risk = compute_risk(qlist)
        d = {
            "fulfillmentText":
            "Hey, you have finished the questionnaire. Here is your risk: %s. Sending monthly updates to you. What's your phone number?"
            % risk
        }
        return jsonify(d)
    elif (risk is not None and phone_number is not None
          and raw_companies is not None):
        print("Raw Companies, if statemetn", raw_companies)
        split = [
            s.lower()
            for s in re.split(';|,|\*|\n|\.|,|!|@|#|$|%|\^|&|\(|\)|-|_| ',
                              raw_companies + ",") if len(s) > 0
        ]
        print("Split", split)
        companies = convert(split)
        print("Conversion of split", companies)

        #return jsonify({"fulfillmentText" : "high mohan"})

        portfolio = Portfolio(risk, companies)
        ret, delta = portfolio.get_market_returns(phone_number)
        print(f"{ret} : {delta}")
        months = 5
        for x in range(months):
            portfolio.get_market_returns(phone_number)
        print(f"{months} months later")
        #d = {"fulfillmentText" : f"Hey, we have added the following: {companies}. Ret: {ret}, Delta: {delta}."}
        #print(f"d: {d}")
        #return jsonify(d)
    return {}
コード例 #40
0
ファイル: views.py プロジェクト: WilliamMayor/snowdrop
def delete():
    for aid in request.get_json().get('aids', []):
        glacier.delete(aid)
    return jsonify(message='OK')
コード例 #41
0
ファイル: api.py プロジェクト: thevops/Simple-REST-API
def get_json_data(*args):
    r = request.get_json(force=True) # ignore mimetype, force parse as JSON
    for arg in args:
        if arg not in r:
            return False
    return r
コード例 #42
0
def new_Car():
    data = {}
    json_data = request.get_json()

    if not json_data.has_key('params') or len(json_data.get('params')) == 0:
        return jsonify({
            "jsonrpc": "2.0",
            "result": False,
            "error": 'incorrect parameters'
        }), 400

    params = request.json.get('params')

    system_all = System.query.first()
    last_car = Car.query.with_entities(Car.no_car).order_by(
        Car.no_car.desc()).first()

    if system_all:
        no_car = system_all.secuence_vehicle + 1
        no_new_car = no_car
    else:
        no_new_car = 1

    if last_car and no_new_car <= last_car[0]:
        no_new_car = last_car[0] + 1

    data.update(dict(secuence_vehicle=no_new_car))
    System.query.first().query.update(data)
    db.session.commit()

    if params.has_key('license_plate') and len(params['license_plate']) != 0:
        license_plate = params['license_plate']
    else:
        return jsonify({
            "jsonrpc": "2.0",
            "result": False,
            "error": 'incorrect parameters'
        }), 400

    if params.has_key('model') and len(params['model']) != 0:
        model = params['model']
    else:
        model = None

    if params.has_key('brand') and len(params['brand']) != 0:
        brand = params['brand']
    else:
        brand = None

    if params.has_key('class_car') and len(params['class_car']) != 0:
        class_car = params['class_car']
    else:
        class_car = None

    if params.has_key('operation_card') and params['operation_card'] > 0:
        operation_card = params['operation_card']
    else:
        operation_card = None

    new_Car_db = Car(no_new_car, license_plate, model, brand, class_car,
                     operation_card)

    db.session.add(new_Car_db)
    db.session.commit()
    return jsonify({
        "jsonrpc": "2.0",
        "result": True,
        "id": new_Car_db.id,
        "no_car": no_new_car
    }), 201
コード例 #43
0
ファイル: retrieve.py プロジェクト: jisung594/tracer-be
def get_price():
    if request.method == 'POST':
        req_obj = request.get_json()
        ticker = req_obj['symbol']

        return requests.get('https://finnhub.io/api/v1/quote?symbol=' + ticker + '&token=' + api_key).content
コード例 #44
0
def index():
    if request.method == 'GET':
        return json.dumps(
            {'error_message': 'You have reached this page in error.'})
    else:
        pass  # Readability, POST request

    full_json = request.get_json()
    full_documents = full_json['documents']
    num_primary_keywords = full_json['num_primary_keywords']
    num_keywords = num_primary_keywords + full_json['num_secondary_keywords']

    num_docs = len(full_documents)

    text_raw, text_final, document_term_frequencies = process_text(
        full_documents)
    named_entities = createNamedEntities(text_raw)

    # Return highest N tf-idf scores for the entire document
    word_ranking = get_word_ranking(text_final, document_term_frequencies,
                                    num_docs, named_entities)

    # alyien_concepts = get_alien_concepts(full_documents)

    sorted_words = sorted(word_ranking, key=itemgetter(1), reverse=True)

    top_words, point_values, total_adjusted_point_values = assign_point_values(
        sorted_words, num_keywords)

    print(
        json.dumps({
            'primary_words':
            top_words[0:num_primary_keywords],
            'primary_point_values':
            point_values[0:num_primary_keywords],
            'named_entities':
            named_entities,
            'secondary_words':
            top_words[num_primary_keywords + 1:],
            'secondary_point_values':
            point_values[num_primary_keywords + 1:],
            'total_points':
            total_adjusted_point_values,
            'error_message':
            None,
            'raw_text':
            text_raw
        }))

    return json.dumps({
        'primary_words':
        top_words[0:num_primary_keywords],
        'primary_point_values':
        point_values[0:num_primary_keywords],
        'named_entities':
        named_entities,
        'secondary_words':
        top_words[num_primary_keywords:],
        'secondary_point_values':
        point_values[num_primary_keywords:],
        'total_points':
        total_adjusted_point_values,
        'error_message':
        None,
        'raw_text':
        text_raw
    })
コード例 #45
0
 def post(self):
     body = request.get_json()
     todo =  Todo(**body).save()
     id = todo.id
     return {'id': str(id)}, 200
コード例 #46
0
ファイル: mock_server.py プロジェクト: cnheider/client-1
 def file_stream(entity, project, run):
     ctx = get_ctx()
     ctx["file_stream"] = ctx.get("file_stream", [])
     ctx["file_stream"].append(request.get_json())
     return json.dumps({"exitcode": None, "limits": {}})
コード例 #47
0
ファイル: api.py プロジェクト: agarmu/conscious-cook
def recipe_info():
    info = {}
    request_json = request.get_json() 
    raw_ingredients = list(set(request_json.keys()))
    for ingredient in raw_ingredients:
        food_name = get_food(ingredient)
        try:
            food_row = food_data.loc[food_name]
        except KeyError:
            continue

        if not food_name:
            continue

        quantity = get_quantity(ingredient)
        if isinstance(quantity, float):
            if "egg" in ingredient:
                grams_per_orig_unit = 60
            else:
                continue
            find_units = False
            units = "eggs"
            n_units = str(quantity)
        elif quantity:
            print("chicken")
            find_units = True
            try:
                food_mass = quantity.to('gram').magnitude
                grams_per_orig_unit = food_mass/quantity.magnitude
            except pint.errors.DimensionalityError:
                 # try volumetric
                try: 
                    conversion_factor = food_row["Density (grams-per-cup)"]
                    if str(conversion_factor) == "nan":
                        continue
                    food_mass = quantity.to('cup') * conversion_factor * ureg.gram/ureg.cup
                    food_mass = food_mass.to_reduced_units().magnitude
                    grams_per_orig_unit = food_mass/quantity.magnitude 
                except pint.errors.DimensionalityError:
                    quantity = None
                    food_mass = None
        else:
            continue

        if find_units:
            try:
                units = str(quantity.units)
            except:
                units = "unknown"
            try:
                n_units = str(quantity.magnitude)
            except: 
                n_units = "unknown"
        per_unit_stats = {
            "calories": str(round(food_row["Calories-per-gram"] * grams_per_orig_unit)),
            "carbon": str(round(food_row["CO2-percent"] * grams_per_orig_unit)),
            "cost": str(round(food_row["Price-per-gram"] * grams_per_orig_unit)),
        }
        info[food_name] = {
            "units": units,
            "n_units": n_units,
            "per_unit": per_unit_stats,
            "element_id": request_json[ingredient],
            "carbon_rating": str(food_row["CO2-percent"]/food_row["Calories-per-gram"]),
            "substitutions": {
               "substitute1_name":{
                    "per_unit": {
                        "calories": 9002,
                        "carbon": 40,
                        "cost": "8.51",
                    }
                } 
            }
        }
    return json.dumps(info)
コード例 #48
0
def add():
    if request.method == 'POST':
        posted_data = request.get_json()
        data = posted_data['data']
        return jsonify(str("Successfully stored  " + str(data)))
コード例 #49
0
ファイル: mock_server.py プロジェクト: cnheider/client-1
 def graphql():
     #  TODO: in tests wandb-username is set to the test name, lets scope ctx to it
     ctx = get_ctx()
     test_name = request.headers.get("X-WANDB-USERNAME")
     app.logger.info("Test request from: %s", test_name)
     if "fail_graphql_times" in ctx:
         if ctx["fail_graphql_count"] < ctx["fail_graphql_times"]:
             ctx["fail_graphql_count"] += 1
             return json.dumps({"errors": ["Server down"]}), 500
     body = request.get_json()
     if body["variables"].get("run"):
         ctx["current_run"] = body["variables"]["run"]
     if body["variables"].get("files"):
         ctx["requested_file"] = body["variables"]["files"][0]
         url = request.url_root + "/storage?file={}&run={}".format(
             urllib.parse.quote(ctx["requested_file"]), ctx["current_run"]
         )
         return json.dumps(
             {
                 "data": {
                     "model": {
                         "bucket": {
                             "id": "storageid",
                             "files": {
                                 "uploadHeaders": [],
                                 "edges": [
                                     {
                                         "node": {
                                             "name": ctx["requested_file"],
                                             "url": url,
                                         }
                                     }
                                 ],
                             },
                         }
                     }
                 }
             }
         )
     if "historyTail" in body["query"]:
         if ctx["resume"] is True:
             hist_tail = '["{\\"_step\\": 15, \\"acc\\": 1, \\"_runtime\\": 60}"]'
             return json.dumps(
                 {
                     "data": {
                         "model": {
                             "bucket": {
                                 "name": "test",
                                 "displayName": "funky-town-13",
                                 "id": "test",
                                 "config": '{"epochs": {"value": 10}}',
                                 "summaryMetrics": '{"acc": 10, "best_val_loss": 0.5}',
                                 "logLineCount": 14,
                                 "historyLineCount": 15,
                                 "eventsLineCount": 0,
                                 "historyTail": hist_tail,
                                 "eventsTail": '["{\\"_runtime\\": 70}"]',
                             }
                         }
                     }
                 }
             )
         else:
             return json.dumps({"data": {"model": {"bucket": None}}})
     if "query Runs(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "project": {
                         "runCount": 4,
                         "readOnly": False,
                         "runs": paginated(run(ctx), ctx),
                     }
                 }
             }
         )
     if "query Run(" in body["query"]:
         return json.dumps({"data": {"project": {"run": run(ctx)}}})
     if "query Model(" in body["query"]:
         if "project(" in body["query"]:
             project_field_name = "project"
             run_field_name = "run"
         else:
             project_field_name = "model"
             run_field_name = "bucket"
         if "commit" in body["query"]:
             run_config = _bucket_config()
         else:
             run_config = run(ctx)
         return json.dumps(
             {"data": {project_field_name: {run_field_name: run_config}}}
         )
     if "query Models(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "models": {
                         "edges": [
                             {
                                 "node": {
                                     "id": "123",
                                     "name": "myname",
                                     "project": "myproj",
                                 }
                             }
                         ]
                     }
                 }
             }
         )
     if "query Projects(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "models": paginated(
                         {
                             "id": "1",
                             "name": "test-project",
                             "entityName": body["variables"]["entity"],
                             "createdAt": "now",
                             "isBenchmark": False,
                         },
                         ctx,
                     )
                 }
             }
         )
     if "query Viewer " in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "viewer": {
                         "entity": "mock_server_entity",
                         "flags": '{"code_saving_enabled": true}',
                         "teams": {
                             "edges": []  # TODO make configurable for cli_test
                         },
                     }
                 }
             }
         )
     if "query Sweep(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "project": {
                         "sweep": {
                             "id": "1234",
                             "name": "fun-sweep-10",
                             "state": "running",
                             "bestLoss": 0.33,
                             "config": yaml.dump(
                                 {"metric": {"name": "loss", "value": "minimize"}}
                             ),
                             "createdAt": datetime.now().isoformat(),
                             "heartbeatAt": datetime.now().isoformat(),
                             "updatedAt": datetime.now().isoformat(),
                             "earlyStopJobRunning": False,
                             "controller": None,
                             "scheduler": None,
                             "runs": paginated(run(ctx), ctx),
                         }
                     }
                 }
             }
         )
     if "mutation UpsertSweep(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "upsertSweep": {
                         "sweep": {
                             "name": "test",
                             "project": {
                                 "id": "1234",
                                 "name": "test",
                                 "entity": {"id": "1234", "name": "test"},
                             },
                         }
                     }
                 }
             }
         )
     if "mutation CreateAgent(" in body["query"]:
         return json.dumps(
             {"data": {"createAgent": {"agent": {"id": "mock-server-agent-93xy",}}}}
         )
     if "mutation Heartbeat(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "agentHeartbeat": {
                         "agent": {"id": "mock-server-agent-93xy",},
                         "commands": json.dumps(
                             [
                                 {
                                     "type": "run",
                                     "run_id": "mocker-server-run-x9",
                                     "args": {"learning_rate": {"value": 0.99124}},
                                 }
                             ]
                         ),
                     }
                 }
             }
         )
     if "mutation UpsertBucket(" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "upsertBucket": {
                         "bucket": {
                             "id": "storageid",
                             "name": body["variables"].get("name", "abc123"),
                             "displayName": "lovely-dawn-32",
                             "project": {
                                 "name": "test",
                                 "entity": {"name": "mock_server_entity"},
                             },
                         },
                         "inserted": ctx["resume"] is False,
                     }
                 }
             }
         )
     if "mutation CreateAnonymousApiKey " in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "createAnonymousEntity": {"apiKey": {"name": "ANONYMOOSE" * 4}}
                 }
             }
         )
     if "mutation PrepareFiles(" in body["query"]:
         nodes = []
         for i, file_spec in enumerate(body["variables"]["fileSpecs"]):
             url = request.url_root + "/storage?file=%s" % file_spec["name"]
             nodes.append(
                 {
                     "node": {
                         "id": str(i),
                         "name": file_spec["name"],
                         "displayName": file_spec["name"],
                         "digest": "null",
                         "uploadUrl": url,
                         "uploadHeaders": "",
                     }
                 }
             )
         return json.dumps({"data": {"prepareFiles": {"files": {"edges": nodes}}}})
     if "mutation CreateArtifact(" in body["query"]:
         collection_name = body["variables"]["artifactCollectionNames"][0]
         return {
             "data": {"createArtifact": {"artifact": artifact(ctx, collection_name)}}
         }
     if "mutation UseArtifact(" in body["query"]:
         return {"data": {"useArtifact": {"artifact": artifact(ctx)}}}
     if "query ProjectArtifactType(" in body["query"]:
         return {
             "data": {
                 "project": {
                     "artifactType": {
                         "id": "1",
                         "name": "dataset",
                         "description": "",
                         "createdAt": datetime.now().isoformat(),
                     }
                 }
             }
         }
     if "query ProjectArtifacts(" in body["query"]:
         return {
             "data": {
                 "project": {
                     "artifactTypes": paginated(
                         {
                             "id": "1",
                             "name": "dataset",
                             "description": "",
                             "createdAt": datetime.now().isoformat(),
                         },
                         ctx,
                     )
                 }
             }
         }
     if "query ProjectArtifactCollections(" in body["query"]:
         return {
             "data": {
                 "project": {
                     "artifactType": {
                         "artifactSequences": paginated(
                             {
                                 "id": "1",
                                 "name": "mnist",
                                 "description": "",
                                 "createdAt": datetime.now().isoformat(),
                             },
                             ctx,
                         )
                     }
                 }
             }
         }
     if "query RunArtifacts(" in body["query"]:
         if "inputArtifacts" in body["query"]:
             key = "inputArtifacts"
         else:
             key = "outputArtifacts"
         artifacts = paginated(artifact(ctx), ctx)
         artifacts["totalCount"] = ctx["page_times"]
         return {"data": {"project": {"run": {key: artifacts}}}}
     if "query Artifacts(" in body["query"]:
         version = "v%i" % ctx["page_count"]
         artifacts = paginated(artifact(ctx), ctx, {"version": version})
         artifacts["totalCount"] = ctx["page_times"]
         return {
             "data": {
                 "project": {
                     "artifactType": {
                         "artifactSequence": {
                             "name": "mnist",
                             "artifacts": artifacts,
                         }
                     }
                 }
             }
         }
     if "query Artifact(" in body["query"]:
         art = artifact(ctx)
         art["artifactType"] = {"id": 1, "name": "dataset"}
         return {"data": {"project": {"artifact": art}}}
     if "query ArtifactManifest(" in body["query"]:
         art = artifact(ctx)
         art["currentManifest"] = {
             "id": 1,
             "file": {
                 "id": 1,
                 "directUrl": request.url_root + "/storage?file=wandb_manifest.json",
             },
         }
         return {"data": {"project": {"artifact": art}}}
     if "stopped" in body["query"]:
         return json.dumps(
             {
                 "data": {
                     "Model": {
                         "project": {"run": {"stopped": ctx.get("stopped", False)}}
                     }
                 }
             }
         )
     print("MISSING QUERY, add me to tests/mock_server.py", body["query"])
     error = {"message": "Not implemented in tests/mock_server.py", "body": body}
     return json.dumps({"errors": [error]})
コード例 #50
0
ファイル: app.py プロジェクト: Megha-KC/Chathuram
def get_table_metadata():
    data = request.get_json()
    table = data.get("table")
    if table not in get_tables_in_db():
        return {"error": "Table does not exist"}, 400
    return {"metadata": get_metadata(table)}, 200
コード例 #51
0
ファイル: main.py プロジェクト: DiarmuidKelly/IOT_Interface
def receive_data():
    print(request.get_json())
    return json.dumps({'success' : True}), 200, {'ContentType' : 'application/json'}
コード例 #52
0
ファイル: app.py プロジェクト: Megha-KC/Chathuram
def create_table_data():
    data = request.get_json()
    print(data)
    # Create table data here
    return {"message": "Successfully Created"}, 200
コード例 #53
0
 def put(self, id):
     return self.get_request_handler(request.headers).update_provider(
         request.get_json(), id)
コード例 #54
0
ファイル: app.py プロジェクト: namickey/k3s-try
def addOrder():
    data = request.get_json()
    pickupSet.add(data['no'])
    return jsonify({
        "orders": str(pickupSet),
    })
コード例 #55
0
ファイル: server.py プロジェクト: JanBartoszek/API-WARS
def logout_user():
    logout_input = request.get_json()
    logic.logout_user()
    session.pop('user:'******'application/json')
コード例 #56
0
ファイル: app.py プロジェクト: namickey/k3s-try
def pickup():
    data = request.get_json()
    pickupSet.pop(data['no'])
コード例 #57
0
ファイル: server.py プロジェクト: JanBartoszek/API-WARS
def get_voted_planets():
    user = request.get_json()
    voted_planets = logic.get_voted_planets(user)
    return json.dumps(voted_planets)
コード例 #58
0
 def tmp_add():
     data_json = request.get_json()
     add(data_json)
     return '应用模板添加成功'
コード例 #59
0
def book_ticket():
    """Books ticket and sends the ticket in email
                    This is using docstrings for specifications. All the parameter values are base64 encoded and are sent.
                    ---
                    parameters:
                      - name: token
                        in: header
                        type: string
                        format: byte
                        required: true
                      - name: email
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: date
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: price
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: from
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: to
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: name
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: count
                        description: number of passengers travelling
                        in: body
                        type: string
                        format: byte
                        required: true
                      - name: payment_info
                        in: body
                        schema:
                            type: object
                            properties:
                                card_number:
                                    type: string
                                    required: true
                                expiry:
                                    type: string
                                    required: true
                                cvv:
                                    type: string
                                    required: true
                        required: true
                    responses:
                      200:
                        schema:
                            type: object
                            properties:
                              message:
                                type: string
                                description: ok if valid, else error
                    """
    response_json = {}
    response_json["message"] = "error"
    global host_URL
    try:
        app.logger.debug(request)
        data = request.get_json()

        # app.logger.debug("Printing")
        app.logger.debug(data)
        email = getDataFromRequest(dataObj=data,keyValue="email")
        date = getDataFromRequest(dataObj=data,keyValue="date")
        price = getDataFromRequest(dataObj=data,keyValue="price")
        frm = getDataFromRequest(dataObj=data,keyValue="from")
        to = getDataFromRequest(dataObj=data,keyValue="to")
        name_on_card = getDataFromRequest(dataObj=data,keyValue="name")
        passenger_count = getDataFromRequest(dataObj=data, keyValue="count")
        ##
        payment_info = data.get("payment_info")
        ######## nested attribute of payment_info#######
        card_number = getDataFromRequest(dataObj=payment_info,keyValue="card_number")
        expiry = getDataFromRequest(dataObj=payment_info,keyValue="expiry")
        cvv = getDataFromRequest(dataObj=payment_info,keyValue="cvv")
        app.logger.debug(cvv)

        validation_response = requests.post(host_URL + "/user", json={"email": data.get("email")}, headers={"token": request.headers['token']})
        # app.logger.debug(validation_response.json())
        validation_response = validation_response.json()
        if validation_response["message"] == "ok":
            response_json["message"] = "ok"
        else:
            return json.dumps(response_json)
        # ##
        # TODO: call payment API
        payment_request_json = {}
        payment_request_json["name"] = name_on_card
        payment_request_json["expiry"] = expiry
        payment_request_json["card_number"] = card_number
        payment_request_json["cvv"] = cvv
        payment_response = requests.post(host_URL+"/payment",json=payment_request_json)
        app.logger.debug(payment_response)
        ##
        card_number = helper.encryptValue(card_number)
        expiry = helper.encryptValue(expiry)
        ##
        tempid = int(time.time()*1000.0)
        table.put_item(
            Item={
                'ID' : tempid,
                'email' : email,
                'date' : date,
                'price' : price,
                'from': frm,
                'to': to,
            }
        )

        table2.put_item(
            Item={
                'Email' : email,
                'Name' : name_on_card,
                'Card' : card_number,
                'Expiry' : expiry,
            }
        )
        ##
        try:
            fp = open("TicketTemplate.html", "r")
            tableTempl = fp.read()
            fp.close()
            ##
            tableTempl = tableTempl.replace("{FROM_PLACE}", frm)
            tableTempl = tableTempl.replace("{TO_PLACE}", to)
            tableTempl = tableTempl.replace("{DATE}", date )
            tableTempl = tableTempl.replace("{PRICE}", price)
            tableTempl = tableTempl.replace("{COUNT}", passenger_count)
            ##
            app.logger.debug(tableTempl)
            attachmentName = str(tempid)+".pdf"
            # pdfkit.from_string(tableTempl,"./app/"+attachmentName)
            HTML(string=tableTempl).write_pdf('./app/' + attachmentName)
            mailTrigger.sendEmail(email,"Ticket Confirmation","Your Ticket is confirmed and is attached",attachmentName)
            os.remove("./app/"+attachmentName)
        except Exception as e:
            app.logger.debug("File error")
            app.logger.debug(e)

    except Exception as e:
        app.logger.debug("Error")
        app.logger.debug(e)
        response_json["message"] = "error"

    return json.dumps(response_json)
コード例 #60
0
ファイル: routes.py プロジェクト: NLIMDb/NLIMDb-API
def get_movie():
    query = request.get_json()
    headers = {'Content-Type': 'application/json'}
    return make_response(PatternMatcher(query).run_pattern_matcher(), 200, headers)