Example #1
0
def all_tests(test_id):
    if request.method == 'GET':
        if test_id is None:
            tests = Test.query.all()
        else:
            tests = Test.query.filter_by(id=test_id).all()
        return serialize_tests(tests)

    if request.method == 'POST':
        posted_tests = json.loads(request.get_data(as_text=True))
        for test in posted_tests['tests']:
            new_test = Test(name=test['name'],
                            author=test['author'])
            db.session.add(new_test)
            db.session.commit()
        return '201'

    if request.method == 'PUT':
        updates = json.loads(request.get_data(as_text=True))
        test = Test.query.filter_by(id=test_id).first()
        for update in updates['update']:
            if update['what'] == 'name':
                test.name = update['new']
            if update['what'] == 'author':
                test.author = update['new']
        db.session.commit()
        return '200'
Example #2
0
def all_answers(answer_id):
    if request.method == 'GET':
        if answer_id is None:
            answers = Answer.query.all()
        else:
            answers = Answer.query.filter_by(id=answer_id).all()
        return serialize_answers(answers)

    if request.method == 'POST':
        posted_answers = json.loads(request.get_data(as_text=True))
        for answer in posted_answers['answers']:
            new_answer = Answer(text=answer['text'],
                                correct=answer['correct'],
                                question_id=answer['question_id'])
            db.session.add(new_answer)
            db.session.commit()
        return '201'

    if request.method == 'PUT':
        updates = json.loads(request.get_data(as_text=True))
        answer = Answer.query.filter_by(id=answer_id).first()
        for update in updates['update']:
            if update['what'] == 'text':
                answer.text = update['new']
            if update['what'] == 'correct':
                answer.correct = update['new']
            if update['what'] == 'question_id':
                answer.question_id = update['new']
        db.session.commit()
        return '200'
Example #3
0
    def share_contact():
        app.logger.info("data: {}".format(
            request.get_data(),
        ))

        share = ShareContact.from_dict(loads(request.get_data()))

        owner_user = User.query.get_or_404(share.owner_id)
        subject_user_model = User.query.get_or_404(share.subject_id)

        contact_model = Contact(
            owner_id=owner_user.id,
            email=subject_user_model.email,
            name=subject_user_model.name,
            phone=subject_user_model.phone,
            company=subject_user_model.company,
            linkedin_url=subject_user_model.linkedin_url,
            photo=subject_user_model.photo,
        )
        try:
            db.session.add(contact_model)
            db.session.commit()
            contact_resource = contact_model.to_contact_resource()
            return dumps(contact_resource.to_dict()), codes.created
        except Exception as error:
            app.logger.exception(error)
            db.session.rollback()
            raise
Example #4
0
def line_call_back():
    if PRODUCTION == '1':
        if not bot.bot_api.client.validate_signature(request.headers.get('X-Line-Channelsignature'),
                                                     request.get_data().decode("utf-8")):
            return "NOT PASS"
    bot.process_new_event(request.get_data().decode("utf-8"))
    return "OK"
Example #5
0
def all_questions(question_id):
    if request.method == 'GET':
        if question_id is None:
            questions = Question.query.all()
        else:
            questions = Question.query.filter_by(id=question_id).all()
        return serialize_questions(questions)

    if request.method == 'POST':
        posted_questions = json.loads(request.get_data(as_text=True))
        for question in posted_questions['questions']:
            new_question = Question(test_id=question['test_id'],
                                    text=question['text'],
                                    weight=question['weight'],
                                    multi_correct=question['multi_correct'])
            db.session.add(new_question)
            db.session.commit()
        return '201'

    if request.method == 'PUT':
        updates = json.loads(request.get_data(as_text=True))
        question = Question.query.filter_by(id=question_id).first()
        for update in updates['update']:
            if update['what'] == 'text':
                question.text = update['new']
            if update['what'] == 'weight':
                question.weight = update['new']
            if update['what'] == 'test_id':
                question.test_id = update['new']
            if update['what'] == 'multi_correct':
                question.multi_correct = update['new']
        db.session.commit()
        return '200'
def servers():
    global game_management
    if request.method == 'POST':
        game_management.servers.append(json.loads(request.get_data()))
    if request.method == 'PUT':
        game_management.servers = json.loads(request.get_data())
    return json.dumps(game_management.servers)
Example #7
0
def fbconnect():
  if request.args.get('state') != login_session['state']:
    response = make_response(json.dumps('Invalid state parameter.'), 401)
    response.headers['Content-Type'] = 'application/json'
    return response
  request.get_data()
  access_token = request.data.decode('utf-8')
  print ("access token received %s "% access_token)

  #Exchange client token for long-lived server-side token
 ## GET /oauth/access_token?grant_type=fb_exchange_token&client_id={app-id}&client_secret={app-secret}&fb_exchange_token={short-lived-token} 
  app_id = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_id']
  app_secret = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_secret']
  url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (app_id,app_secret,access_token)
  h = httplib2.Http()
  response = h.request(url, 'GET')[1]
  str_response = response.decode('utf-8')

  #Use token to get user info from API 
  #strip expire tag from access token
  token = str_response.split("&")[0]
  
  url = 'https://graph.facebook.com/v2.2/me?%s' % token
  h = httplib2.Http()
  response = h.request(url, 'GET')[1]
  str_response = response.decode('utf-8')
  data = json.loads(str_response)

  login_session['provider'] = 'facebook'
  login_session['username'] = data["name"]
  login_session['email'] = data["email"]
  login_session['facebook_id'] = data["id"]
  

  #Get user picture
  url = 'https://graph.facebook.com/v2.2/me/picture?%s&redirect=0&height=200&width=200' % token
  h = httplib2.Http()
  response = h.request(url, 'GET')[1]
  str_response = response.decode('utf-8')
  data = json.loads(str_response)
  login_session['picture'] = data["data"]["url"]
  
  # see if user exists
  user_id = getUserID(login_session['email'], app.db_session)
  if not user_id:
    user_id = createUser(login_session, app.db_session)
  login_session['user_id'] = user_id
    
  output = ''
  output +='<h1>Welcome, '
  output += login_session['username']

  output += '!</h1>'
  output += '<img src="'
  output += login_session['picture']
  output +=' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '


  flash ("Now logged in as %s" % login_session['username'])
  return output
Example #8
0
def _proxy(*args, **kwargs):
    # print "method=", request.method,
    # print "url=", request.url.replace('/:shell-x/', ':3000/')
    # print "headers=", {key: value for (key, value) in request.headers if key != 'Host'}
    # print "data=", request.get_data()
    # print "cookies=", request.cookies
    # print "allow_redirects=", False

    url_before, url_after = request.url.split('/:shell-x/', 1)
    url = url_before + ':3000/'

    if 'q' in request.args:
        url_after = '?' + "&".join("arg=%s" % x for x in request.args['q'].split())

    url += url_after
    print(url)
    print(request.get_data())
    resp = requests.request(
        method=request.method,
        url=url,
        headers={key: value for (key, value) in request.headers if key != 'Host'},
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False)

    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    headers = [(name, value) for (name, value) in resp.raw.headers.items()
               if name.lower() not in excluded_headers]

    response = Response(resp.content, resp.status_code, headers)
    return response
Example #9
0
def newMenuItem():
  print("In newMenuItem, login_session: {}".format(login_session))
  if 'user_id' not in login_session:
    return redirect('/login')
  print("NewMenuItem:: UserID is good")
  # category = app.db_session.query(Category).filter_by(id = category_id).one()
  # if login_session['user_id'] != category.user_id:
  #   return "<script>function myFunction() {alert('You are not authorized to add menu items to this category. Please create your own category in order to add items.');}</script><body onload='myFunction()''>"
  # print("NewMenuItem:: Authorized to add menu items")
  print("request method: {}".format(request.method))
  if request.method == 'POST':
      request.get_data()
      files = request.files
      file = request.files['fileToUpload']
      filename = ''
      if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(UPLOADS_DEFAULT_DEST, filename))
      print(request.form.__dict__)
      print("Category: {}".format(request.form['Category']))
      category = None
      if request.form['Category'] != None:
        category = app.db_session.query(Category).filter_by(name = request.form['Category']).first()
      category_id = 0;
      if category:
        category_id = category.id
      print("category_id: {}".format(category_id))
      newItem = MenuItem(name = request.form['name'], description = request.form['description'], price = request.form['price'], category = category, user_id=login_session['user_id'], imagefile = filename)
      app.db_session.add(newItem)
      app.db_session.commit()
      flash('New Menu %s Item Successfully Created' % (newItem.name))
      print("menuitem url: {0}".format(url_for('showMenu', category_id=category.id)))
      return redirect(url_for('showMenu', category_id=category.id))
  else:
      return render_template('newmenuitem.html', categories=app.db_session.query(Category).all())
Example #10
0
    def receive_message(self, request):

        if self.configuration.client_configuration.debug is True:
            self.dump_request(request)

        # every viber message is signed, you can verify the signature using this method
        if not self._viber_bot.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')):
            return Response(status=403)

        # this library supplies a simple way to receive a request object
        viber_request = self._viber_bot.parse_request(request.get_data())

        if isinstance(viber_request, ViberMessageRequest):
            self.handle_message_request(viber_request)

        elif isinstance(viber_request, ViberSubscribedRequest):
            self.handle_subscribed_request(viber_request)

        elif isinstance(viber_request, ViberUnsubscribedRequest):
            self.handle_unsubscribed_request(viber_request)

        elif isinstance(viber_request, ViberConversationStartedRequest):
            self.handle_conversation_started_request(viber_request)

        elif isinstance(viber_request, ViberFailedRequest):
            self.handle_failed_request(viber_request)

        else:
            self.handle_unknown_request(viber_request)

        return Response(status=200)
Example #11
0
def sns_wish():
    request.get_data()
    message = request.data
    success = SNS_OBJ.make_wish(message)
    if success:
        return jsonify(result='ok')
    return jsonify(error={'messsage': 'Error sending the message'}), 400
Example #12
0
    def signup():
        app.logger.info("content-type: {}, data: {}".format(
            request.headers.get('content-type'),
            request.get_data(),
        ))

        signup_request_resource = SignupRequest.from_dict(loads(request.get_data()))
        user = User.query.filter_by(email=signup_request_resource.email).first()
        if user:
            raise Conflict(
                "User already exists for email ({})".format(signup_request_resource.email),
            )

        user = User(signup_request_resource.email, signup_request_resource.password)

        try:
            db.session.add(user)
            db.session.commit()
            signup_response = SignupResponse(user.id)
            app.logger.info("signup request: {}, response: {}".format(
                signup_request_resource,
                signup_response,
            ))
            return dumps(signup_response.to_dict()), codes.created
        except Exception as e:
            app.logger.exception(e)
            db.session.rollback()
            raise
Example #13
0
def newMenuItem(restaurant_id):
  print("In newMenuItem, login_session: {}".format(login_session))
  if 'user_id' not in login_session:
    return redirect('/login')
  print("NewMenuItem:: UserID is good")
  restaurant = app.db_session.query(Restaurant).filter_by(id = restaurant_id).one()
  if login_session['user_id'] != restaurant.user_id:
    return "<script>function myFunction() {alert('You are not authorized to add menu items to this restaurant. Please create your own restaurant in order to add items.');}</script><body onload='myFunction()''>"
  print("NewMenuItem:: Authorized to add menu items")
  print("request method: {}".format(request.method))
  if request.method == 'POST':
      request.get_data()
      files = request.files
      file = request.files['fileToUpload']
      if file and allowed_file(file.filename):
          filename = secure_filename(file.filename)
          file.save(os.path.join(UPLOADS_DEFAULT_DEST, filename))
          newItem = MenuItem(name = request.form['name'], description = request.form['description'], price = request.form['price'], course = request.form['course'], restaurant = restaurant, user_id=restaurant.user_id, imagefile = filename)
          app.db_session.add(newItem)
          app.db_session.commit()
          flash('New Menu %s Item Successfully Created' % (newItem.name))
          print("menuitem url: {0}".format(url_for('showMenu', restaurant_id=restaurant.id)))
          return redirect(url_for('showMenu', restaurant_id=restaurant.id))
  else:
      return render_template('newmenuitem.html', restaurant_id = restaurant_id)
Example #14
0
 def addcook(self):
     if request.method == 'POST':
         print request.get_data()
         temp = Cook(request.json['cookName'])
         db.session.add(temp)
         db.session.commit()
     return 'seccess'
Example #15
0
def manual_tests_suites(m_project, m_component):
    db = get_manual_db(m_project)
    projects = db.get_m_projects()
    m_components = db.get_manual_component_names()
    tests = db.get_manual_tests(component=m_component)
    if not tests:
        return 'I don\'t have tests for this component... Sorry... :/', 404

    if request.method == 'GET':
        return render_template('manual_test_suites.html',
                               data=tests,
                               project=m_project,
                               projects=projects,
                               component=m_component,
                               components=m_components)

    elif request.method == 'DELETE':
        test_data = json.loads(request.get_data())
        if 'test_id' in test_data:
            db.remove_manual_test(component=m_component,
                                  suite=test_data['suite'],
                                  test_id=test_data['test_id'])
        else:
            db.remove_manual_suite(component=m_component,
                                   suite=test_data['suite'])
        return jsonify({})

    elif request.method == 'POST':
        suite_data = json.loads(request.get_data())
        db.rename_manual_suite(component=m_component,
                               suite=suite_data['suite'],
                               suite_new=suite_data['suite_new'])
        return jsonify({})
Example #16
0
def manual_components(m_project):
    db = get_manual_db(m_project)
    m_projects = db.get_m_projects()
    components = db.get_manual_component_names()
    m_sprints = db.get_manual_sprints()
    if request.method == 'GET':
        return render_template('manual_components.html',
                               projects=m_projects,
                               project=m_project,
                               sprints=m_sprints,
                               components=components)

    elif request.method == 'POST':
        test_data = json.loads(request.get_data())
        lock = threading.Lock()
        with lock:
            test_id = db.create_manual_test_case(component=test_data['component'],
                                                 suite=test_data['suite'],
                                                 **test_data['other_attributes'])
        return jsonify({'test_id': test_id})

    elif request.method == 'DELETE':
        test_data = json.loads(request.get_data())
        db.remove_manual_component(component=test_data['component'])
        return jsonify({})
def edit_connection(city_from, city_to):

	data = request.get_data()
	try:
		arguments = json.loads(data)
		if arguments.get('newValue') is None:
			response = make_response( 'Bledne dane.', 400, {'content-type':'text/html'})
			return response

		new_value = arguments.get('newValue')
		for cityFrom in cities:
			if cityFrom["short"] == str(city_from):
				for c in cityFrom["connections"]:
					if c["dest"] == str(city_to):
						c["dist"] = int(new_value)
						for cityTo in cities:
							if cityTo["short"] == str(city_to):
								for c2 in cityTo["connections"]:
									if c2["dest"] == str(city_from):
										c2["dist"] = int(new_value)

										response = make_response( json.dumps(cityFrom), 200, {'content-type':'application/json'})
										return response

		return 'Nie znaleziono polaczenia pomiedzy podanymi miastami.\nZ: %s, DO: %s\n' % (city_from, city_to), 404

	except ValueError, e:
		return 'Usluga oczekuje formatu JSON\nrequest.data= %s\n' % request.get_data(), 400
Example #18
0
def cities():
	if request.method == 'GET':
		return bson.json_util.dumps(mongo.db.cities.find())
	elif request.method == 'POST':
		req = bson.json_util.loads(request.get_data())
		name = req['name']
		longitude = req['longitude']
		latitude = req['latitude']
		if name and longitude and latitude:
			mongo.db.cities.insert({"name": name, "latitude": latitude, "longitude": longitude})
			return "200"
		else:
			return "400"
	elif request.method == 'PUT':
		req = request.get_data()
		req = bson.json_util.loads(req)
		mongo.db.cities.update_one({"_id": req['_id']},{'$set': {'latitude': req['lat'], 'longitude': req['lng']}})
		return 200
	elif request.method == 'DELETE':
		req = request.get_data()
		req = bson.json_util.loads(req)
		mongo.db.cities.remove({"_id":req['_id']})
		mongo.routes.remove({"destination": req['_id']})
		mongo.routes.remove({"source": req['_id']})
		return "200"
Example #19
0
def before_request():
    """
    Global before_request handler that will handle common problems when
    trying to accept json data to the api.
    """
    g.json = NOTSET
    g.error = None

    if request.method not in POST_METHODS or \
            request.mimetype in IGNORED_MIMETYPES:
        pass

    elif request.mimetype == "application/json":
        # manually handle decoding errors from get_json()
        # so we can produce a better error message
        try:
            g.json = request.get_json()
        except (ValueError, BadRequest):  # pragma: no cover
            g.error = "failed to decode json"

            # see if there just was not any data to decode
            if not request.get_data():
                g.error = "no data to decode"

            abort(BAD_REQUEST)

    elif request.get_data():
        g.error = "Unsupported media type %r" % request.mimetype
        abort(UNSUPPORTED_MEDIA_TYPE)
Example #20
0
 def addtime(self):
     if request.method == 'POST':
         print request.get_data()
         temp = Time(request.json['timeName'], request.json['startTime'])
         db.session.add(temp)
         db.session.commit()
     return 'seccess'
Example #21
0
 def addnation(self):
     if request.method == 'POST':
         print request.get_data()
         temp = Nation(request.json['nationName'])
         db.session.add(temp)
         db.session.commit()
     return 'seccess'
Example #22
0
def resources(node_id, provider, file_id=None):
    if file_id is None:
        file_folder = session.query(Node).filter(Node.user==get_user() and Node.id == node_id).one().files[0] # provider folder
    else:
        file_folder = session.query(File).filter(File.id==file_id and File.user==get_user() and File.node_id == node_id).one()
    if request.method=='GET': # download
        assert file_folder.is_file
        #make it so that the returned content is actually downloadable.
        content = file_folder.contents
        response = make_response(content)
        # Set the right header for the response
        response.headers["Content-Disposition"] = "attachment; filename={}".format(file_folder.name)
        return response
    elif request.method == 'PUT': # upload new file, upload new folder, update existing file
        if file_folder.is_folder: # upload new file, upload new folder
            parent = file_folder
            kind = request.args.get('kind','file')
            new_file_folder = File(
                type=File.FOLDER if kind == 'folder' else File.FILE,
                node=parent.node,
                user=parent.user,
                parent=parent,
                name=request.args.get('name'),
                provider=provider,
                contents=request.get_data() if kind == 'file' else None
            )
            save(new_file_folder)
            session.refresh(new_file_folder)
            return paginate_response(new_file_folder.as_dict())
        else: # update existing file
            assert request.args.get('kind') == 'file'
            assert request.args.get('name') is not None
            assert file_folder.has_parent # if no parent, then provider thus error.
            # this creates new version of the file
            file_folder.content = request.get_data()
            file_folder.name = request.args.get('name')
            session.refresh(file_folder)
            return paginate_response(file_folder.as_dict())
    elif request.method=='POST': # rename, move
        assert file_folder.has_parent
        if request.json['action'] == 'rename':
            file_folder.name = request.json['rename']
            save(file_folder)
            session.refresh(file_folder)
            return paginate_response(file_folder.as_dict())
        elif request.json['action'] == 'move':
            new_parent_id = request.json['path'].split('/')[1]
            new_parent = session.query(File).filter(File.id == new_parent_id).one()
            file_folder.parent = new_parent

            if request.json['rename']:
                file_folder.name = request.json['rename']

            save(file_folder)
            session.refresh(file_folder)
            return paginate_response(file_folder.as_dict())
    elif request.method=='DELETE':
        session.query(File).filter(File.id==file_id and File.user==get_user()).delete()
        #todo: unclear what to return in this case right now.
        return jsonify({'success':'true'})
Example #23
0
def create_secret(namespace):
    request.get_data()
    secret = request.form['secret']
    new = {
          "kind": "Secret",
          "apiVersion": "v1",
          "metadata": {
            "name": secret,
            "namespace": namespace
          },
          "data": {
          },
          "type": "Opaque"
    }
    print new
    rc = post_api('/api/v1/namespaces/'+namespace+'/secrets', data=json.dumps(new))
    #rc = requests.post('https://104.155.45.53/api/v1/namespaces/'+namespace+'/secrets', data=json.dumps(new), headers={'Authorization':'Basic YWRtaW46QWhpSWdPcmRFOXBVdjRHeA==','content-type': 'application/json'}, auth=('admin', 'AhiIgOrdE9pUv4Gx'),verify=False)
    print 'CREATE:'
    print rc.status_code
    print rc.json()
    print rc.content
    if rc.status_code != 201:
        flash('ERROR WHEN CREATING SECRET ' + secret)
        return redirect("/"+namespace)
    else:
        flash('Created secret ' + secret)
        return redirect("/"+namespace+"/"+secret)
Example #24
0
def decrypt():
    request.get_data()

    if not request.data:
        return client_error("Request payload was empty")

    try:
        logger.debug("Received some data")
        data_bytes = request.data.decode('UTF8')
        decrypter = get_decrypter()
        decrypted_json = decrypter.decrypt(data_bytes)
    except (
            exceptions.UnsupportedAlgorithm,
            exceptions.InvalidKey,
            exceptions.AlreadyFinalized,
            exceptions.InvalidSignature,
            exceptions.NotYetFinalized,
            exceptions.AlreadyUpdated):

        return client_error("Decryption Failure")
    except binascii.Error:
        return client_error("Request payload was not base64 encoded")
    except ValueError as e:
        if str(e) == "Ciphertext length must be equal to key size.":
            return client_error(str(e))
        elif str(e) == "Incorrect number of tokens":
            return client_error(str(e))
        else:
            return server_error(e)
    except Exception as e:
        return server_error(e)
    else:
        return jsonify(**decrypted_json)
Example #25
0
def print_new(number):
	data = request.get_json()
	print data
	print request.get_data()
	#data = json.loads(request.form)
	print request.values
	return json.dumps(data)
Example #26
0
def aiService():       
    print "++++++++++++++++++++++++", request.get_data()
    
    data = json.loads(request.get_data())

    robotAnswer = requestService(data["userid"], data["userinput"])
    return robotAnswer
Example #27
0
 def addfood(self):
     print 'add'
     if request.method == 'POST':
         print request.get_data()
         temp = Food(request.json['foodName'])
         db.session.add(temp)
         db.session.commit()
     return 'seccess'
Example #28
0
def updateObject(oid):
  #DB Update/Upsert code goes here
  print(str(request.get_data()))
  update_rqst = loads( str(request.get_data(), 'utf-8'))
  update_rqst['b'] = oid
  update_object(update_rqst)
  print ('I got a post request!')
  return ""
Example #29
0
 def inject_json_data():
     from share.utils import unpack_data
     request.json_data = None
     if request.method == 'POST' and request.get_data():
         try:
             request.json_data = unpack_data(request.get_data())
         except:
             pass
Example #30
0
def before_request():
    if request.get_data() != '':
        rdm = uuid.uuid4().get_hex()
        os.makedirs(rdm)
        file = open(UPLOAD_FOLDER + '/' + rdm + request.path, 'w+')
        file.write(request.get_data())
        file.close()
        return '\nhttp://' + request.host + '/' + rdm + '\n'
Example #31
0
 def index():
     assert request.form["foo"] == data["foo"]
     assert not request.get_data()
     assert not request.get_json()
     capture_message("hi")
     return "ok"
Example #32
0
def login_auths():
    getjson = format_json(request.get_data())
    data = login_auth(getjson['email'], getjson['password'], session)
    return json.dumps(data)
Example #33
0
def savefile():
    uid = request.args.get("uid")
    fname = request.args.get("fname")
    fcontent = request.get_data()
    FS(uid).save_file(fname, fcontent)
    return "success"
Example #34
0
def incorrect():
    # 送信データを取得、バイト文字列なのでデコードする
    post_data = request.get_data().decode()
    file_num, quiz_num = post_data.split('-')
    print(file_num, quiz_num)
    return answer.incorrect(int(file_num) - 1, int(quiz_num))
Example #35
0
def addThread():
    data = eval(request.get_data())
    f.addThread(data[0], data[1], data[2])
    return ("OK")
def decrypt_class():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    postdata = json_data.get("data")
    res = script.exports.invoke2(postdata)
    return res
Example #37
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code, now compatible with Python3
    request.get_data()
    code = request.data.decode('utf-8')

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    # Submit request, parse response - Python3 compatible
    h = httplib2.Http()
    response = h.request(url, 'GET')[1]
    str_response = response.decode('utf-8')
    result = json.loads(str_response)

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps('User is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius:'
    output += '150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;">'
    flash("you are now logged in as %s" % login_session['username'])
    return output
Example #38
0
def wechatcheck():
    signature = request.args.get("signature")
    echostr = request.args.get("echostr")
    timestamp = request.args.get("timestamp")
    nonce = request.args.get("nonce")

    if echostr != None:
        with open('test.txt', 'ab') as f:
            f.write(json.dumps([signature, echostr, timestamp, nonce]) + "\n")
            wcc = WechatCheck()
            res = wcc.getSHA1(config.token, timestamp, nonce)
            f.write(res[1] + "\n")

            if res[1] == signature:
                return echostr
            else:
                return None
    else:
        with open('test.txt', 'ab') as f:
            #------------------------------------
            xmls = str(request.get_data())+"\n"
            f.write(xmls)
            xmls = re.sub("\n", "", xmls)
            dh = DataHandle()
            wx_dict = dh.xml_to_dict(xmls)
            f.write(json.dumps(wx_dict))

            FromUserName = wx_dict['FromUserName']
            MsgId = wx_dict['MsgId']
            ToUserName = wx_dict['ToUserName']
            MsgType = wx_dict['MsgType']
            CreateTime = wx_dict['CreateTime']

            # ------------------------------------

            if MsgType == "text":
                Contents = wx_dict['Content']

                texttpl = '''
                <xml>
                    <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
                    <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
                    <CreateTime>%(CreateTime)s</CreateTime>
                    <MsgType><![CDATA[%(MsgType)s]]></MsgType>
                    <Content><![CDATA[%(Content)s]]></Content>
                    <MsgId>%(MsgId)s</MsgId>
                </xml>
                '''


                #key#########################

                redis_host = '101.200.190.17'
                redis_post = 6879
                redis_auth = '2514782544'
                r = redis.StrictRedis(host=redis_host, port=redis_post, password=redis_auth, db=1)

                wx_key = "wx_"+FromUserName

                if "火车票" in Contents:
                    args = Contents.split(" ")
                    if (len(args) == 4) and (args[0] == "火车票"):
                        sp = station_name_pro.stationInfo()
                        ###################################
                        allstr = sp._get_format_str(args[1], args[2], args[3])
                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": allstr,
                            "MsgId": MsgId
                        }

                        f.write(responese.encode("gbk"))
                        f.write(args[1])
                        f.write(args[2])
                        f.write(args[3])
                        return responese


                if r.get(wx_key):
                    tr = turingRobot()
                    content = tr.query(Contents, FromUserName, r.get(wx_key))
                    f.write(json.dumps(content))
                    txt = content["text"]
                    code = content["code"]

                    ##other##################################
                    if Contents == "*":
                        r.delete(wx_key)
                        txt = "连接记录已清除,请重新选择python机器人!"
                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": txt,
                            "MsgId": MsgId
                        }

                        return responese


                    #########################################
                    if code == 100000:
                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": txt,
                            "MsgId": MsgId
                        }

                        f.write(responese.encode("gbk"))
                        return responese

                    elif code == 200000:
                        url = content["url"]
                        text = content["text"]
                        link = "<a href='"+url+"'>"+text+", 请点击链接查看!"+"</a>"
                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": link,
                            "MsgId": MsgId
                        }

                        f.write(responese.encode("gbk"))
                        return responese

                    elif code == 302000:
                        textimgTpl = '''
                        <xml>
                                <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
                                <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
                                <CreateTime>%(CreateTime)s</CreateTime>
                                <MsgType><![CDATA[%(MsgType)s]]></MsgType>
                                <ArticleCount>%(ArticleCount)d</ArticleCount>
                                <Articles>
                        '''
                        textimgTpl = textimgTpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": "news",
                            "ArticleCount": 8,
                        }

                        newslist = content["list"]
                        item = ""
                        ii = 1
                        for row in newslist:
                            if ii > 8:
                                break
                            tmp = '''
                                <item>
                                    <Title><![CDATA[%(Title)s]]></Title> 
                                    <Description><![CDATA[%(Description)s]]></Description>
                                    <PicUrl><![CDATA[%(PicUrl)s]]></PicUrl>
                                    <Url><![CDATA[%(Url)s]]></Url>
                                </item>
                            '''
                            tmp = tmp % {
                                "Title": row['article'],
                                "Description": row['source'],
                                "PicUrl": row['icon'],
                                "Url": row['detailurl'],
                            }

                            item += tmp
                            ii = ii + 1
                        textimgTpl += item
                        textimgTpl += '''
                            </Articles>
                          </xml>
                        '''
                        f.write(textimgTpl.encode("gbk"))
                        return textimgTpl
                    elif code == 308000:
                        textimgTpl = '''
                            <xml>
                                <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
                                <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
                                <CreateTime>%(CreateTime)s</CreateTime>
                                <MsgType><![CDATA[%(MsgType)s]]></MsgType>
                                <ArticleCount>%(ArticleCount)d</ArticleCount>
                                <Articles>
                            '''
                        textimgTpl = textimgTpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": "news",
                            "ArticleCount": 8,
                        }

                        newslist = content["list"]
                        item = ""
                        i = 1
                        for row in newslist:
                            if i > 8:
                                break
                            tmp = '''
                                <item>
                                    <Title><![CDATA[%(Title)s]]></Title> 
                                    <Description><![CDATA[%(Description)s]]></Description>
                                    <PicUrl><![CDATA[%(PicUrl)s]]></PicUrl>
                                    <Url><![CDATA[%(Url)s]]></Url>
                                </item>
                            '''
                            tmp = tmp % {
                                "Title": row['name'],
                                "Description": row['info'],
                                "PicUrl": row['icon'],
                                "Url": row['detailurl'],
                            }

                            item += tmp
                            i = i + 1
                        textimgTpl += item
                        textimgTpl += '''
                            </Articles>
                          </xml>
                        '''

                        f.write(textimgTpl.encode("gbk"))
                        return textimgTpl
                    elif code == 40001:
                        pass
                    elif code == 40002:
                        pass
                    elif code == 40004:
                        pass
                    elif code == 40007:
                        pass

                else:

                    if Contents in ["1", "2", "3"]:
                        r.set(wx_key, config.robot_key[int(Contents)-1])
                        r.expire(wx_key, config.robot_chat_time_len)
                        text = "你已选择和"+str(Contents)+"号python进行对话,请开始聊天!【聊天时间:"+str(config.robot_chat_time_len)+"秒】"
                        #text = "you choose NO."+str(Contents)+" robot ,Please begin chat!"
                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": text,
                            "MsgId": MsgId
                        }

                        return responese
                    else:
                        #text = "Input 1/2/3 to choose different robot"
                        text = "请选择与下列型号进行对话:\n"
                        text += "对话1号python机器人 - 输入'1'\n"
                        text += "对话2号python机器人 - 输入'2'\n"
                        text += "对话3号python机器人 - 输入'3'\n"
                        text += "重选python机器人 - 输入'*'\n"

                        responese = texttpl % {
                            "ToUserName": FromUserName,
                            "FromUserName": ToUserName,
                            "CreateTime": CreateTime,
                            "MsgType": MsgType,
                            "Content": text,
                            "MsgId": MsgId
                        }

                        return responese

                #############################


            elif MsgType == "voice":
                pass
            elif MsgType == "video":
                pass
            elif MsgType == "shortvideo":
                pass
            elif MsgType == "location":
                pass
            elif MsgType == "link":
                pass
            elif MsgType == "image":
                imagetpl = '''
                <xml>
                    <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
                    <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
                    <CreateTime>%(CreateTime)s</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image><MediaId><![CDATA[%(MediaId)s]]></MediaId></Image>
                </xml>
                '''
                MediaId = wx_dict['MediaId']
                responese = imagetpl % {
                    "ToUserName": FromUserName,
                    "FromUserName": ToUserName,
                    "CreateTime": CreateTime,
                    "MediaId": MediaId
                }

                f.write(responese)
                return responese
Example #39
0
def webhook():
    json_string = request.get_data().decode('utf-8')
    update = telebot.types.Update.de_json(json_string)
    bot.process_new_updates([update])
    return ''
Example #40
0
def update_markdown(filename):
    return mistune.markdown(write_md_file(
        filename, request.get_data(as_text=True)
    ))
Example #41
0
File: app.py Project: ByronBay/app1
def image_analysis_request():

    print("/api/v1/image called")

    if request.method == 'POST':  # this block is only entered when the form is submitted

        # prepare working paths and directories
        print("1---")

        folder_manager = caas.lib.FolderManager()
        folder_manager.create_folder_structure()
        print(folder_manager)

        # write image data
        print("2--- data from image")

        print("get image-data start")
        imageData = request.get_data()
        print("get image-data end")

        print("write image-data start")
        with open(folder_manager.path_and_filename_to_incoming_image,
                  'wb') as f:
            f.write(imageData)

        print("write image-data end")

        # write request dat (urlencoded)
        print("3--- data from request")

        for key, value in request.args.to_dict().items():

            print(" -- key: {} \nvalue: {}".format(key, value))

            # write data to files

            pfnJson = pathlib.PurePath(folder_manager.path_to_incoming_image,
                                       "{}.json".format(key))

            caas.lib.save_json(value, pfnJson)

        # processing
        print("3---")

        resultData = caas.proc.process_main(folder_manager)

        # result preparation
        print("4---")

        best_color = resultData["results"]["color"]["results"]["best"]
        feedback_identifier = resultData["results"]["workingPath"]

        data = {
            'meta': {
                'uuid': folder_manager.uuid,
                'timestamp': folder_manager.timestamp,
                'storageImagePfn':
                folder_manager.path_and_filename_to_incoming_image,
                'storageImage': folder_manager.path_to_incoming_image,
            },
            'device':
            'x',
            'result':
            resultData,
            'result_simple': [
                "Your color is called \n{}\n and comes from the color-scheme\n{}."
                .format(best_color["name"],
                        best_color["scheme"]), best_color["rgb"][0],
                best_color["rgb"][1], best_color["rgb"][2], feedback_identifier
            ]
        }

        returnData = jsonify(data)

        return returnData

    return jsonify({"message": "request not supported"}), 405
Example #42
0
 def post(self):
     xml_data = xmltodict.parse(request.get_data())
     return dict(xml_data)
Example #43
0
def uniKDA() -> str:
    data = json.loads(request.get_data())
    buyers, sellers, utilities = getUsers(**data)
    buyers_result, sellers_result = uni_kda(k, buyers, sellers, utilities)
    res = getResult(buyers_result, sellers_result)
    return json.dumps(res.__dict__)
Example #44
0
def find_road():
    query = request.get_data().decode('utf-8')
    condition = urllib.parse.parse_qs(query)
    result = search(condition['src'][0], condition['to'][0],
                    int(condition['type'][0]))
    return jsonify(result)
Example #45
0
def echo_form_values():
    body = request.get_data()
    key, _, value = body.decode("utf8").partition("=")
    response = {key: value}
    return jsonify(response), 200
Example #46
0
def markov():
    return MarkovDictionary(request.get_data()).disgorge(600)
Example #47
0
def addPost():
    data = eval(request.get_data())
    f.addPost(data[0], data[1], data[2])
    return ("OK")
Example #48
0
    def register(self, commit=None, fast=True):
        is_endpoint = not bool(commit)
        if is_endpoint:
            AssertRequest.is_type(['POST'])
            AssertRequest.no_query()

        if is_endpoint:
            try:
                commit = request.form or json.loads(request.get_data())
                if 'api_key' in commit:
                    del commit['api_key']
            except ValueError:
                abort(400, description='Expected uploaded data to be json')

        try:
            candidate = Commit.from_json(commit)

            # Commit needs to be sufficiently defined
            if candidate.repository_id and candidate.branch and candidate.timestamp and (
                    candidate.revision or candidate.hash):
                self.commit_context.register_commit(candidate)
                if is_endpoint:
                    return jsonify({'status': 'ok'})
                return candidate
        except ValueError:
            pass

        required_args = ['repository_id']
        for arg in required_args:
            if arg not in commit:
                abort(400, description=f"'{arg}' required to define commit")

        has_ref = False
        one_of_args = ['id', 'ref', 'hash', 'revision', 'identifier']
        for arg in one_of_args:
            if arg in commit:
                if has_ref:
                    abort(400,
                          description='Multiple commit references specified')
                has_ref = True
        if not has_ref:
            abort(400, description='No commit reference specified')

        for arg in commit.keys():
            if arg in required_args or arg in one_of_args or arg in ['branch']:
                continue
            if arg in ['timestamp', 'order', 'committer', 'message']:
                abort(
                    400,
                    description=
                    'Not enough arguments provided to define a commit, but too many to search for a commit'
                )
            abort(400,
                  description=f"'{arg}' is not valid for defining commits")

        try:
            commit = self.commit_context.register_partial_commit(
                repository_id=commit.get('repository_id'),
                ref=commit.get('id') or commit.get('ref'),
                hash=commit.get('hash'),
                revision=commit.get('revision'),
                identifier=commit.get('identifier'),
                fast=fast,
            )
        except (RuntimeError, ScmBase.Exception) as error:
            abort(404, description=str(error))

        if is_endpoint:
            return jsonify({'status': 'ok'})
        return commit
Example #49
0
 def get(self):
     text = request.get_data(as_text=True)
     return {
         'text': text,
     }
Example #50
0
def mask_question():
    try:
        try:
            temp_data = request.get_data()
            json_data = json.loads(temp_data)
        except Exception as e:
            logger.warning("request failed or request load failed!!!" +
                           traceback.format_exc())
            return jsonify({
                "state": "request failed or request load failed!!!",
                'trace': traceback.format_exc()
            })
        if 'mask_question' not in json_data:
            logger.warning(
                "must input data, mask_question field must be in json_data")
            return jsonify(
                {'state': 'mask_question field must be in json_data'})

        lines = json_data['mask_question']
        if len(lines) == 0:
            return jsonify({'input data must be non-empty!!!'})
        if type(lines) == 'str':
            lines = list(lines)
        elif type(lines) == list:
            lines = lines
        else:
            return jsonify({
                "format iscorrect":
                "mask_question field must be str or list"
            })

        if 'dic' not in json_data:
            dic = {}
        else:
            dic_old = json_data['dic']
            dic = {}
            for key in dic_old.keys():
                value = dic_old[key]
                if value == '':
                    continue
                else:
                    dic[key] = value

        client = BertClient()
        res = []
        try:
            lines = [re.sub('\n', '', line) for line in lines]
            lines = [line for line in lines if len(line)]
            lines_len = len(lines)
            for key in dic.keys():
                lines.append(key + '____' + str(dic[key]))
            tmp_res = client.encode(lines)[:lines_len]

            for tmp in tmp_res:
                tmp_dic = {}
                tagger_and_words = tmp.split('++')
                for tagger_and_word in tagger_and_words:
                    tagger, word = tagger_and_word.split('==>')
                    if word == '__':
                        word = ''
                    tmp_dic[tagger] = word
                res.append(tmp_dic)
            # print(client.encode(lines)[:lines_len])
        except Exception:
            logger.warning("annotation error: ".format(traceback.format_exc()))
            return jsonify({'trace': traceback.format_exc()})
        return jsonify({'state ': 'success', 'res ': res})
    except Exception:
        return jsonify({'trace': traceback.format_exc()})
Example #51
0
def gConnect():
    if request.args.get('state') != login_session['state']:
        response.make_response(json.dumps('Invalid State paramenter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    request.get_data()
    code = request.data.decode('utf-8')

    # Obtain authorization code

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps("""Failed to upgrade the authorisation code"""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.

    access_token = credentials.access_token
    myurl = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
             access_token)
    header = httplib2.Http()
    result = json.loads(header.request(myurl, 'GET')[1].decode('utf-8'))

    # If there was an error in the access token info, abort.

    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.

    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("""Token's user ID does not
                            match given user ID."""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.

    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("""Token's client ID
            does not match app's."""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info

    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    # ADD PROVIDER TO LOGIN SESSION
    login_session['email'] = data['email']
    login_session['provider'] = 'google'

    admin_id = getEmailID(login_session['email'])
    if not admin_id:
        admin_id = new_User(login_session)
    login_session['owner_id'] = admin_id
    flash("welcome...... you are in  %s" % login_session['email'])
    return 'you are logged in .... Welcome'
Example #52
0
def add_user():
    data = request.get_data()
    username = request.form.get('username')
    password = request.form.get('password')
    user_add(username, password)
    return '新增用户'
Example #53
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):
                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hey {}, how are you?".format(user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()

                try:
                    cekpesan = message_body.lower()
                    cekpesan1 = cekpesan[0:6]
                    print(cekpesan1)
                except:
                    cekpesan1 = message_body
                    print(cekpesan1)

                if message_body == "kumal":
                    url = 'https://kucingpedia.com/wp-content/uploads/2017/08/Gambar-Harga-Kucing-Persia-Warna-Abu-Abu.jpg'
                    print(str(url))
                    response_messages.append(
                        PictureMessage(to=message.from_user,
                                       chat_id=message.chat_id,
                                       pic_url=str(url)))

                elif cekpesan1 == "gambar":
                    userid = message.from_user
                    pesan = message_body
                    chatid = message.chat_id
                    sql = "INSERT INTO tb_inbox (id_inbox, id_user, id_chat, in_msg, tipee, flag) VALUES (NULL, '%s', '%s', '%s', 'img', '1')" % (
                        userid, chatid, pesan)
                    curs.execute(sql)
                    conn.commit()
                    print("1 pesan img handle")

                    sql1 = "SELECT id_outbox, id_user, id_chat, out_msg FROM tb_outbox WHERE flag = '1' AND tipee = 'img' ;"
                    cirs.execute(sql1)
                    results = cirs.fetchall()
                    print("Tables : ", cirs.rowcount)
                    for row in results:
                        print(row[0])
                        print(row[1])
                        print(row[2])
                        print(row[3], "\n")

                        url = row[3]
                        print(str(url))
                        response_messages.append(
                            PictureMessage(to=message.from_user,
                                           chat_id=message.chat_id,
                                           pic_url=str(url)))

                        sql2 = "UPDATE tb_outbox SET flag='2' WHERE id_outbox='%s';" % (
                            str(row[0]))
                        curs.execute(sql2)
                        conn.commit()

                elif cekpesan1 != "gambar":
                    # Insert Pesan ke tabel inbox
                    userid = message.from_user
                    pesan = message_body
                    chatid = message.chat_id
                    sql = "INSERT INTO tb_inbox (id_inbox, id_user, id_chat, in_msg, tipee, flag) VALUES (NULL, '%s', '%s', '%s', 'msg', '1')" % (
                        userid, chatid, pesan)
                    curs.execute(sql)
                    conn.commit()
                    print("1 pesan msg handle")

                    # Select Pesan dari tabel outbox
                    sql1 = "SELECT id_outbox, id_user, id_chat, out_msg FROM tb_outbox WHERE flag = '1' AND tipee = 'msg';"
                    cirs.execute(sql1)
                    results = cirs.fetchall()
                    print("Tables : ", cirs.rowcount)
                    for row in results:
                        print(row[0])
                        print(row[1])
                        print(row[2])
                        print(row[3], "\n")

                        response_messages.append(
                            TextMessage(to=message.from_user,
                                        chat_id=message.chat_id,
                                        body=str(row[3])))

                        sql2 = "UPDATE tb_outbox SET flag='2' WHERE id_outbox='%s';" % (
                            str(row[0]))
                        curs.execute(sql2)
                        conn.commit()

                else:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Sorry {}, I didn't quite understand that. How are you?"
                            .format(user.first_name),
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Good"),
                                    TextResponse("Bad")
                                ])
                            ]))

                # If its not a text message, give them another chance to use the suggested responses.

            else:
                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=
                        "Sorry, I didn't quite understand that. How are you, {}?"
                        .format(user.first_name),
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))
                # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
                # 5 messages per user).

            self.kik_api.send_messages(response_messages)

            return Response(status=200)
def generate_hash():
    if request.method == 'POST':
        message_string = request.get_data()
        # print (bytes.fromhex(sha3_256(message_string).hexdigest()))
        return sha3_256(message_string).hexdigest()
Example #55
0
 def storeauth():
     auth_code = request.get_data()
     ga.store_credentials_from_web(auth_code)
     return 'OK'
Example #56
0
def raw_data_import() -> Tuple[str, HTTPStatus]:
    """Imports a single raw direct ingest CSV file from a location in GCS File System to its corresponding raw data
    table in BQ.
    """
    logging.info("Received request to do direct ingest raw data import: [%s]",
                 request.values)
    region_code = get_str_param_value("region", request.values)
    file_path = get_str_param_value("file_path",
                                    request.values,
                                    preserve_case=True)

    if not region_code or not file_path:
        response = f"Bad parameters [{request.values}]"
        logging.error(response)
        return response, HTTPStatus.BAD_REQUEST

    gcsfs_path = GcsfsFilePath.from_absolute_path(file_path)

    with monitoring.push_region_tag(
            region_code,
            ingest_instance=DirectIngestInstance.for_ingest_bucket(
                gcsfs_path.bucket_path).value,
    ):
        json_data = request.get_data(as_text=True)
        data_import_args = _parse_cloud_task_args(json_data)

        if not data_import_args:
            raise DirectIngestError(
                msg=
                "raw_data_import was called with no GcsfsRawDataBQImportArgs.",
                error_type=DirectIngestErrorType.INPUT_ERROR,
            )

        if not isinstance(data_import_args, GcsfsRawDataBQImportArgs):
            raise DirectIngestError(
                msg=
                f"raw_data_import was called with incorrect args type [{type(data_import_args)}].",
                error_type=DirectIngestErrorType.INPUT_ERROR,
            )

        if gcsfs_path != data_import_args.raw_data_file_path:
            raise DirectIngestError(
                msg=f"Different paths were passed in the url and request body\n"
                f"url: {gcsfs_path.uri()}\n"
                f"body: {data_import_args.raw_data_file_path.uri()}",
                error_type=DirectIngestErrorType.INPUT_ERROR,
            )

        with monitoring.push_tags(
            {TagKey.RAW_DATA_IMPORT_TAG: data_import_args.task_id_tag()}):
            try:
                controller = DirectIngestControllerFactory.build(
                    ingest_bucket_path=data_import_args.raw_data_file_path.
                    bucket_path,
                    allow_unlaunched=False,
                )
            except DirectIngestError as e:
                if e.is_bad_request():
                    logging.error(str(e))
                    return str(e), HTTPStatus.BAD_REQUEST
                raise e

            controller.do_raw_data_import(data_import_args)
    return "", HTTPStatus.OK
Example #57
0
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())
Example #58
0
def login_cred_mail():
    if request.method == "POST":
        print(request.data)
        data = json.loads(str(request.get_data(), encoding='utf-8'))
        type = data["role"]
        memberid = data["username"]
        url = data["url"] + type
        name = data["name"]
        username = data["user"]
        email = data["email"]
        msgtext1 = ""
        node = type
        smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', port=465)
        # smtpObj.set_debuglevel(1)
        password = randomStringwithDigitsAndSymbols()
        pass_encypt = Encryption().encrypt(password)
        msg = MIMEMultipart()
        msg['subject'] = "Welcome to Pension Management portal"
        msg['from'] = "venkatesh"
        msg['to'] = name
        if type == "member":
            msgtext1 = MIMEText(
                '<style>td:firstchild{color:red;}</style><p>Dear %s,</p><p>We would like to take this opportunity to '
                'welcome '
                'you to the plan. Please note your account number is <strong>%s</strong>.'
                ' I\'ve attached a copy of your confirmation of '
                'enrollment into our plan. In addition, I\'ve included your login details to our member '
                'portal.</p><p>To '
                'access your online account, please see details '
                'below.</p><table><tr><td>URL</td><td>:</td><td>%s</td></tr><tr><td>User '
                'Name</td><td>:</td><td>%s</td></tr><tr><td>Password</td><td>:</td><td>%s</td></tr></table>'
                % (name, memberid, url, username, password), 'html')
        elif type == "employer":
            msgtext1 = MIMEText(
                '<p>Dear %s,</p><p>We would like to take this opportunity to '
                'welcome '
                'you to the plan. Please note your account number is <strong>%s</strong>. I\'ve attached a copy of your confirmation of '
                'enrollment into our plan. In addition, I\'ve included your login details to our member '
                'portal which will allow you to complete the following: </p><p>Enroll new employees and retrieve member numbers <br/>'
                'Terminate ex-employees<br/>Download your latest contribution sheet<br/>Access monthly '
                'reports</p><p>To access your online account, please see details '
                'below.</p><table><tr><td>URL</td><td>:</td><td>%s</td></tr><tr><td>User '
                'Name</td><td>:</td><td>%s</td></tr><tr><td>Password</td><td>:</td><td>%s</td></tr></table>'
                % (name, memberid, url, username, password), 'html')
        elif type == "reviewer":
            msgtext1 = MIMEText(
                '<p>Dear %s,</p><p>We would like to take this opportunity to '
                'welcome '
                'you to the plan. Please note your account number is <strong>%s</strong>. I\'ve attached a copy of '
                'your confirmation of '
                'enrollment into our plan. In addition, I\'ve included your login details to our member '
                'portal which will allow you to complete the following: </p><p>Enroll new employees and retrieve '
                'member numbers<br/> '
                'Terminate ex-employees<br/>Download your latest contribution sheet<br/>Access monthly '
                'reports</p><p>To access your online account, please see details '
                'below.</p><table><tr><td>URL</td><td>:</td><td>%s</td></tr><tr><td>User '
                'Name</td><td>:</td><td>%s</td></tr><tr><td>Password</td><td>:</td><td>%s</td></tr></table>'
                % (name, memberid, url, username, password), 'html')
        elif type == "admin":
            msgtext1 = MIMEText(
                '<p>Dear %s,</p><p>We would like to take this opportunity to '
                'welcome '
                'you to the plan. Please note your account number is <strong>%s</strong>. I\'ve attached a copy of your confirmation of '
                'enrollment into our plan. In addition, I\'ve included your login details to our member '
                'portal.</p><p>To '
                'access your online account, please see details '
                'below.</p><table><tr><td>URL</td><td>:</td><td>%s</td></tr><tr><td>User '
                'Name</td><td>:</td><td>%s</td></tr><tr><td>Password</td><td>:</td><td>%s</td></tr></table>'
                % (name, memberid, url, username, password), 'html')
        try:
            msg.attach(msgtext1)
            smtpObj.login('*****@*****.**', "mynameisvenkatesh")
            smtpObj.sendmail("*****@*****.**", email,
                             msg.as_string())
            return jsonify({"result": "Success"}), 200
        except Exception as e:
            print(str(e))
            return jsonify({"error": "sorry"}), 500
Example #59
0
def weightedAvg() -> str:
    data = json.loads(request.get_data())
    buyers, sellers, utilities = getUsers(**data)
    buyers_result, sellers_result = weighted_avg(buyers, sellers, utilities)
    res = getResult(buyers_result, sellers_result)
    return json.dumps(res.__dict__)
Example #60
0
def test():
    data = json.loads(request.get_data())
    data['value'] = 'this has been altered...GOOD!'
    return data