def createUser(): """ Linux user will be created """ _name = request.form['inputName'] if find_user(_name): return json.dumps({'message':'User already exists !'}) if not check_valid(_name): return json.dumps({'message':'User can be created entered length should be less than 32 !'}) _password = request.form['inputPassword'] # Check if user to be created with sudo rights '''if _sudo: os.system("echo RANDOM | sudo -S adduser "+_name+" sudo ") return json.dumps({'message':'User created successfully !'})''' enc_pass = crypt.crypt(_password,"22") if os.getegid()!=0: os.system("echo "+SUDO_PASSWORD+" | sudo -S useradd -p "+enc_pass+" "+_name) else: os.system("useradd -p "+enc_pass+" "+_name) return json.dumps({'message':'User created successfully !'})
def ajaxSubmit(): """ Handles HTTP requests (GET and POST) that are sent through ajax (i.e. without control of page redirection). :return: A serialized json object that contains the session information to be used in javascript """ postRequest = request.json or request.form # Short circuit the data fetch print postRequest print postRequest.getlist('answer') alist = eval("".join(postRequest.getlist('answer'))) if alist == []: return json.dumps({"session_info": SESSION_INFO.toJson()}) dna.answer(alist) dna.newQ() print dna.currentquestion if dna.currentquestion == -1 or dna.currentquestion == "error": print "error got" SESSION_INFO.result = dna.currentList q = Question() q.qid = "-1" SESSION_INFO.question = q return json.dumps({"session_info": SESSION_INFO.toJson()}) SESSION_INFO.question = dna.currentquestion.toQestion() return json.dumps({"session_info": SESSION_INFO.toJson()})
def jsonify(data, status=200, headers=None): if not isinstance(data, (dict, list)): raise TypeError # Determine JSON indentation indent = None if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr: indent = 2 # Determine if this is a JSONP request callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + json.dumps({ 'meta': { 'status': status, }, 'data': data, }, indent=indent) + ')' mimetype = 'application/javascript' status = 200 else: content = json.dumps(data, indent=indent) mimetype = 'application/json' return current_app.response_class( content, mimetype=mimetype, headers=headers), status
def ACrearTarea(): #POST/PUT parameters params = request.get_json() results = [{'label':'/VHistoria', 'msg':['Tarea creada']}, {'label':'/VHistoria', 'msg':['No se pudo crear tarea.']}, ] res = results[0] # Obtenemos el id de la historia actual idHistory = int(session['idHistoria']) # Extraemos los parámetros taskDesc = params['descripcion'] idCategoria = params['categoria'] taskPeso = params['peso'] if 'iniciado' in params: started = params['iniciado'] else: started = False if 'fechaInicio' in params: startingDate= params['fechaInicio'] try: startingDate_object = datetime.strptime(startingDate, '%d/%m/%Y') except ValueError: res = results[1] res['label'] = res['label'] + '/'+str(idHistory) return json.dumps(res) else: startingDate_object = None oBackLog = backlog() oTask = task() if 'miembro' in params: miembro = params['miembro'] else: miembro = None insert = oTask.insertTask(taskDesc, idCategoria, taskPeso, idHistory, started, startingDate_object) insertedTask = oTask.searchTask(taskDesc)[0] if miembro == None or miembro < 0: oTask.deleteUserTask(int(insertedTask.HW_idTask)) else: oTask.insertUserTask(int(insertedTask.HW_idTask), int(miembro)) if insert: res = results[0] else: res = results[1] res['label'] = res['label'] + '/' + str(idHistory) if "actor" in res: if res['actor'] is None: session.pop("actor", None) else: session['actor'] = res['actor'] return json.dumps(res)
def userName(): """ Récupère le nom et prénom d'un utilisateur Args: request.form doit contenir : - login : identifiant unique de connexion Returns: code 1, data : utilisateur trouvé, data contient l'utilisateur avec le nom et prénom code -1, message : erreur de connexion """ try: conn = Connexion().connect() consumer = ConsumerDAO() if request.method == 'POST': login = request.form["login"] consFilt = consumer.getByFilter(conn, False, [], ('login', login)) if consFilt != None: cons = Consumer(firstname=consFilt.firstname, name=consFilt.name) resp = {"code" : 1, "data" : json.dumps(cons.serial(), encoding="utf-8")} else: resp = {"code" : -1, "message" : "Utilisateur inconnu"} except: Connexion().exception() resp = {"code" : -1, "message" : "Erreur inconnue lors de la récupération du nom utilisateur"} finally: Connexion().disconnect(conn) return json.dumps(resp, encoding="utf-8")
def signUp(): try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # validate the received values if _name and _email and _password: # All Good, let's call MySQL conn = mysql.connect() cursor = conn.cursor() _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def VEquipo(): #GET parameter idPila = request.args['idPila'] res = {} if "actor" in session: res['actor']=session['actor'] #Action code goes here, res should be a JSON structure if 'usuario' not in session: res['logout'] = '/' return json.dumps(res) idPila = int(session['idPila']) oTeam = team() teamList = oTeam.getTeam(idPila) oUser = user() userList = oUser.getAllUsers() res['fEquipo'] = {'lista':[{'miembro':team.EQ_username, 'rol': team.EQ_rol} for team in teamList]} res['usuario'] = session['usuario'] res['idPila'] = idPila res['fEquipo_opcionesRol'] =[ {'key':'Desarrollador', 'value':'Desarrollador'}, {'key':'Scrum master', 'value':'Scrum master'}, ] res['fEquipo_opcionesMiembros'] =[{'key':user.U_username,'value': user.U_username} for user in userList] #Action code ends here return json.dumps(res)
def get_rules(): try: c = db.cursor() return json.dumps(c.execute('SELECT * FROM rules').fetchall()) except: print_exc() return json.dumps({})
def get_rule(ruleId): try: c = db.cursor() return json.dumps(c.execute('SELECT * FROM rules WHERE id=:id', { "id": ruleId }).fetchall()) except: print_exc() return json.dumps({})
def submitAnswer(): try: _answer= request.form['inputAnswer'] if _answer : # All Good, let's call MySQL conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_checkAnswer',(_answer)) data = cursor.fetchall() print data[0] if data[0] == (u'Correct!',): return render_template('correct.html') else: return render_template ('incorrect.html') else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def logIn(): try: # get the inputed information _email = request.form['inputEmail'] _password = request.form['inputPassword'] # validate the received values if _email and _password: #call MySQL conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_checkUser',(_email,_password)) data = cursor.fetchall() # if user valid, rendesrs next page: if len(data) is 0: conn.commit() return render_template('insertCode.html') else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) # close connection to MySQL finally: cursor.close() conn.close()
def VCrearObjetivo(): res = {} # Producto actual. idProducto = session['idPila'] res['fObjetivo_opcionesTransversalidad'] = [ {'key':0, 'value':'No'}, {'key':1, 'value':'Si'},] # Se almacena la información recibida. res['fObjetivo'] = {'idPila': idProducto, 'idObjetivo':request.args.get('idObjetivo',1), 'descripcion':request.args.get('descripcion',''), 'transversal':request.args.get('transversal',0)} res['idPila'] = idProducto if "actor" in session: res['actor']=session['actor'] if 'usuario' not in session: res['logout'] = '/' return json.dumps(res) res['usuario'] = session['usuario'] return json.dumps(res)
def submitCode(): try: _code = request.form['inputCode'] _location = request.form['inputLocation'] if _code and _location: conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_getEnigma',(_code,_location)) data = cursor.fetchall() print data[0] if data[0] != (u'Wrong code inserted !',): return render_template('enigma1.html') else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def __call__(self, field, **kwargs): kwargs['data-role'] = u'select2-ajax' kwargs['data-url'] = url_for('.ajax_lookup', name=field.loader.name) allow_blank = getattr(field, 'allow_blank', False) if allow_blank and not self.multiple: kwargs['data-allow-blank'] = u'1' kwargs.setdefault('id', field.id) kwargs.setdefault('type', 'hidden') if self.multiple: result = [] ids = [] for value in field.data: data = field.loader.format(value) result.append(data) ids.append(as_unicode(data[0])) separator = getattr(field, 'separator', ',') kwargs['value'] = separator.join(ids) kwargs['data-json'] = json.dumps(result) kwargs['data-multiple'] = u'1' else: data = field.loader.format(field.data) if data: kwargs['value'] = data[0] kwargs['data-json'] = json.dumps(data) return HTMLString('<input %s>' % html_params(name=field.name, **kwargs))
def signUp(): try: # read the posted values from the UI address = request.form['inputAddress'] email = request.form['inputEmail'] # validate the received values if address and email: conn = mysql.connect() cursor = conn.cursor() # adds user to db if cursor.execute('select (1) from users where email = %s limit 1', (email)): return render_template("alreadyused.html") else: # creates user cursor.execute('insert into users (email,zone) values (%s,%s)', (email,address)) # sends confirmation email token = key.dumps(email, salt='email-confirm-key') confirm_url = url_for('confirm_email',token=token,_external=True) subject = "Confirm Your Email" html = render_template('emailconfirm.html',confirm_url=confirm_url) send_email(email, subject, html) conn.commit() return render_template('confirmation.html') else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error2':str(e)}) finally: cursor.close() conn.close()
def update(): try: mysql.connect() with mysql.cursor() as cursor: if session.get('user'): _title = request.form['title'] _country = request.form['country'] _description = request.form['description'] _destination_id = request.form['id'] _filePath = request.form['filePath'] _tag = request.form['tag'] cursor.callproc('sp_updateWish',(_title,_country,_description,_destination_id.split(),_filePath,_tag)) data = cursor.fetchall() if len(data) is 0: mysql.commit() return json.dumps({'status':'OK'}) else: return json.dumps({'status':'ERROR'}) else: return ('Unauthorized Access') except Exception as e: return json.dumps({'status':'Unauthorized access'}) finally: cursor.close() mysql.close()
def signUp(): try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # Valida os dados recebidos if _name and _email and _password: with closing(mysql.connect()) as conn: with closing(conn.cursor()) as cursor: _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User criado com sucesso!'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>preencha os campos requeridos</span>'}) except Exception as e: return json.dumps({'error':str(e)})
def get_data(): try: request_data = \ { "ip": request.remote_addr, "callback": request.args.get("callback", False), "tags": request.args.get("tags", False) } #init data provider data_provider = DataProvider(request_data) #get data from provider response_data = data_provider.get_data() #make json response_json = json.dumps(response_data) if request_data["callback"]: response_json = "{0}({1})".format(request_data["callback"], json.dumps(response_data)) return Response(response=response_json, status=200, mimetype="application/json", headers={"P3P": "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD " "IVAi IVDi CONi HIS OUR IND CNT\""}) except Exception, e: logger.exception(e) response = Response(response=None, status=200) return response
def test_is_json_serializable(self): class Tester(db.Document): extras = db.ExtrasField() @Tester.extras('dict') class ExtraDict(db.Extra): def validate(self, value): if not isinstance(value, dict): raise db.ValidationError('Should be a dict instance') @Tester.extras('embedded') class EmbeddedExtra(db.EmbeddedDocument): name = db.StringField(required=True) tester = Tester(extras={ 'test': {'key': 'value'}, 'embedded': EmbeddedExtra(name='An embedded field'), 'string': 'a value', 'integer': 5, 'float': 5.5, }) self.assertEqual(json.dumps(tester.extras), json.dumps({ 'test': {'key': 'value'}, 'embedded': {'name': 'An embedded field'}, 'string': 'a value', 'integer': 5, 'float': 5.5, }))
def updateWish(): try: if session.get('user'): _user = session.get('user') _title = request.form['title'] _description = request.form['description'] _wish_id = request.form['id'] _filePath = request.form['filePath'] _isPrivate = request.form['isPrivate'] _isDone = request.form['isDone'] conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_updateWish',(_title,_description,_wish_id,_user,_filePath,_isPrivate,_isDone)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'status':'OK'}) else: return json.dumps({'status':'ERROR'}) except Exception as e: return json.dumps({'status':'Unauthorized access'}) print e finally: cursor.close() conn.close()
def edit_note(note_id): if session.get('active'): noteJSON = json.loads(request.data) # get note with ID from DB note = db_session.query(Note).filter_by(idNote = note_id).first() # update note with new values note.title = noteJSON["title"] note.text = noteJSON["text"] # commit changes to database db_session.commit() js = json.dumps({ "error":"none" , "message":"ok" }) resp = Response(js , status=200, mimetype="application/json") return resp else: js = json.dumps({ "error":"session" , "message":"inactive" }) resp = Response(js , status=406, mimetype="application/json") return resp
def AElimCategoria(): if 'usuario' not in session: res['logout'] = '/' return json.dumps(res) identificador = int(request.args['idCategoria']) results = [{'label':'/VCategorias', 'msg':['Categoría eliminada.']}, {'label':'/VCategorias', 'msg':['Error al intentar eliminar categoría.']}, ] res = results[0] cates = clsCategoria() eliminarCorrecto = cates.eliminar(identificador) if(eliminarCorrecto): res = results[0] ###res['label'] = res['label'] + '/' #Action code ends here if "actor" in res: if res['actor'] is None: session.pop("actor", None) else: session['actor'] = res['actor'] return json.dumps(res)
def set_garbage(): j = sanitize_set_garbage(request.get_json(force=True,silent=True)) if not j: example = json.dumps({ "id":"123", "price_bonus":12.34 }) return json.dumps({ 'error': ('provide a valid json body! example: %s' % (example,)) }), 400 with db.session_scope() as session: tid = j['id'] try: task = session.query(db.OpenTask).filter(db.OpenTask.id == tid).one() except NoResultFound: return json.dumps({ 'error': 'id does not exists' }), 400 except MultipleResultsFound: return json.dumps({ 'error': 'more than one result found' }), 400 logger.info("set garbage called with task id %d", task.id) session.delete(task) session.commit() result = { 'error': None, 'success': True }, 200 return json.dumps(result)
def runtask(): rpc = app.config['scheduler_rpc'] if rpc is None: return json.dumps({}) projectdb = app.config['projectdb'] project = request.form['project'] project_info = projectdb.get(project, fields=('name', 'group')) if not project_info: return "no such project.", 404 if 'lock' in projectdb.split_group(project_info.get('group')) \ and not login.current_user.is_active(): return app.login_response newtask = { "project": project, "taskid": "on_start", "url": "data:,on_start", "process": { "callback": "on_start", }, "schedule": { "age": 0, "priority": 9, "force_update": True, }, } ret = rpc.newtask(newtask) return json.dumps({"result": ret}), 200, {'Content-Type': 'application/json'}
def task(): j = sanitize_post_task(request.get_json(force=True,silent=True)) if not j: example = { "id":"123", "task_description":"Is company mentioned positive/neutral/negative in the following paragraph?", "task_text":"lorem ipsum ...", "answer_possibilities":["yes","no","neutral"], "callback_link":"http://localhost:5000/webook", "price":12.34 } return json.dumps({ 'error': 'provide a valid json body!', 'example': example }), 400 with db.session_scope() as session: tid = j['id'] if session.query(db.OpenTask).filter(db.OpenTask.id == tid).count() != 0: return json.dumps({ 'error': 'id already exists' }), 400 answers = j['answer_possibilities'] answer = None if type(answers) is type([]): answer = "|".join(answers) elif answers == 'text': answer = "text" else: return json.dumps({ 'error': 'answer_possibilities must either be of type list ["yes","no",...] or "text"' }), 400 open_task = db.OpenTask(j['id'], j['task_description'], j['task_text'], answer, j['callback_link'], j['price']) session.add(open_task) session.commit() result = { 'error': None, 'success': True } return json.dumps(result)
def send_email(): email_fields = json.loads(request.data) errors = [] fields_validated = validate_email_fields(email_fields, errors) # Return 400 status if fields are not valid if not fields_validated: return make_response(json.dumps(errors), "400", {}) # Send via Mailgun first: mailgun_response = send_via_mailgun(email_fields) if mailgun_response == 200: email_fields["service"] = "mailgun" email_fields["service_response"] = json.dumps(mailgun_response.json()) save_to_db(email_fields) return make_response() # Mailgun failed -- Send via Mailgun: mandrill_response = send_via_mandrill(email_fields) if mandrill_response[0]["status"] == "sent": email_fields["service"] = "mandrill" email_fields["service_response"] = json.dumps(mandrill_response[0]) save_to_db(email_fields) return make_response() return make_response("Both email services failed", "400", {})
def signUp(): try: #read the posted values from the UI _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] #validate the received values if _name and _email and _password: #We call the MySQL conn = mysql.connect() cursor = conn.cursor() #prepare a cursor object using cursor() method _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) #If the procedure is executed successfully, we commit the changes and return the success message: data = cursor.fetchall() #fetch all of the rows from the query if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span> Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def ACrearCategoria(): if 'usuario' not in session: res['logout'] = '/' return json.dumps(res) params = request.get_json() results = [{'label':'/VCategorias', 'msg':['Categoría creada.']}, {'label':'/VCategorias', 'msg':['Error al intentar crear categoría.']}, {'label':'/VCategorias', 'msg':['Solo puede crear categorias el Scrum Master.']} ] res = results[1] usuarioActual = session['usuario'] infoUsuarioActual = Users.query.filter(Users.username == usuarioActual).first() nombre = params.get('nombre',None) peso = params.get('peso',None) if (infoUsuarioActual.actor == 'SM' ): if (( nombre != None ) and ( peso != None )): categoria = clsCategoria() creaccionCorrecta = categoria.insertar(nombre,peso) res = results[0] if creaccionCorrecta[0] else results[1] else: res = results[2] if "actor" in res: if res['actor'] is None: session.pop("actor", None) else: session['actor'] = res['actor'] return json.dumps(res)
def upload(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): # Determine the extension of the file extension = os.path.splitext(file.filename)[1] # Generate unique filename f_name = str(uuid.uuid4()) + extension # Check the upload folder exists, otherwise create it # Check the uploads folder exists, otherwise create it print("INFO: Checking if upload folder exists") if not os.path.exists(application.config['UPLOAD_FOLDER']): try: print("WARN: Upload folder does not exist, creating it") os.makedirs(application.config['UPLOAD_FOLDER']) except Exception as e: print(e) # Save file file.save(os.path.join(application.config['UPLOAD_FOLDER'], f_name)) # Resize file #devices = resizr.ResizeForAll(application.config['UPLOAD_FOLDER'] + "/" + f_name) #print(devices) return json.dumps({'filename':f_name}) else: return json.dumps({'error':'Invalid filetype, JPG only!'})
def AModifCategoria(): if 'usuario' not in session: res['logout'] = '/' return json.dumps(res) params = request.get_json() results = [{'label':'/VCategorias', 'msg':['Categoría actualizada.']}, {'label':'/VCategorias', 'msg':['Error al intentar modificar categoría.']}, ] # Resultado de la modificación de la categoría. res = results[1] identificador = int(session['idCategoria']) nombre = params.get('nombre', None) peso = params.get('peso', None) if ((nombre != None) and (peso != None )): categoria = clsCategoria() modificacionCorrecta = categoria.modificar(identificador, nombre, peso) res = results[0] if modificacionCorrecta else results[1] if "actor" in res: if res['actor'] is None: session.pop("actor", None) else: session['actor'] = res['actor'] return json.dumps(res)
def test_delete_meetups_with_wrong_user(self): result = self.app.delete('/api/v1/meetups/2', data=json.dumps({"userid": 1})) data = json.loads(result.data) self.assertEqual(result.status_code, 403) self.assertEqual(data['message'], "Forbidden: Record not owned")
def process(): url = request.json.get("url", None) if not url: return json.dumps({'error': "%s not received" % url}, ensure_ascii=False) return json.dumps({'info': session['research_process' + url]}, ensure_ascii=False)
def response( data ): return application.response_class( response=json.dumps(data), status=200, mimetype='application/json' )
def store_to_redis(key, obj): """Save json-serializable object to redis""" redis_store.set(key, json.dumps(obj))
def _infodump(obj, indent=2): msg = json.dumps(obj, indent=indent) logger.info(msg)
`端子号(DDF/ODF架号-子模块号-端子号)`, `收/发`, 备注, 对应10G波长转换板 from %s.%s""" % (dbname,tablename) try: g.cursor.execute(sql) except Exception,e: print e abort(400) for row in g.cursor.fetchall(): #row是一个列值的tuple。((A1,B1,C1),(A2,B2,C2),(A3,B3,C3)) data = dict(zip(field_names, row)) datas.append(data) return json.dumps(datas) @bp.route('/export_dispatch_excel', methods=["POST"]) def export_dispatch_excel(): rowindex = 1 content = json.loads(request.form["content"]) ISOTIMEFORMAT = "%y-%m-%d-%H_%M_%S" lt = time.localtime() ft = time.strftime(ISOTIMEFORMAT, lt) file_path = current_app.config['DISPATCH_TEMPLATE'] rb = xlrd.open_workbook(file_path, formatting_info=True) w = copy(rb) wb = w.get_sheet(0)
def test_delete_nonexisting_meetups(self): result = self.app.delete('/api/v1/meetups/500', data=json.dumps({"userid": 1})) data = json.loads(result.data) self.assertEqual(result.status_code, 404) self.assertEqual(data['message'], "Meetup does not exist")
def test_update_user_didnt_create_comment(self): data = json.dumps({"comment": "Postponed", "userid": 2}) result = self.app.put('/api/v1/meetups/1/comment', data=data) self.assertEqual(result.status_code, 403)
def json_api_error(e): response = {"message": str(e)} status_code = 500 if hasattr(e, "status_code"): status_code = e.status_code return make_response(json.dumps(response), status_code, JSON_HEADERS)
def test_delete_meetups(self): result = self.app.delete('/api/v1/meetups/3', data=json.dumps({"userid": 1})) data = json.loads(result.data) self.assertEqual(data["status"], 204) self.assertEqual(data['message'], "Meetups record has been deleted")
def json_created(location): response = {"message": "created"} headers = {} headers.update(JSON_HEADERS) headers["Location"] = location return make_response(json.dumps(response), 201, headers)
def test_update_with_empty_values(self): data = json.dumps({}) result = self.app.put('/api/v1/meetups/1/location', data=data) self.assertEqual(result.status_code, 400) data = json.loads(result.data) self.assertEqual(data['message'], "location/userid is not present")
def canvas(): data = getData() response = app.response_class(response=json.dumps(data), status=200, mimetype='application/json') return response
def json_response(obj): return make_response(json.dumps(obj), 200, JSON_HEADERS)
def user(): user = dict(session) if 'name' in session else {} return json.dumps(user)
def census_income(): data = getIncome() response = app.response_class(response=json.dumps(data), status=200, mimetype='application/json') return response
def users_del(id): models.users.deldata(id) return json.dumps({"code": 0, "msg": "完成!"})
def pictures(user, thread): return json.dumps( sorted(os.listdir( os.path.join(app.config['UPLOAD_FOLDER'], user, thread)), key=lambda x: os.path.splitext(x)[0]))
def jsonpify(callback_name, data): data = callback_name + '(' + json.dumps(data) + ')' response = make_response(data) response.mimetype = 'text/javascript' return response
def users_edit(id): if request.method == 'GET': group_list = authorModels.authGroup.all() group_list_data = [] for item in group_list: group_list_data.append({"id":item.id, "title":item.title}) if id: data_list = models.users.find_by_id(id) result = {} result["id"] = data_list.id result["username"] = data_list.username result["password"] = data_list.password result["nickname"] = data_list.nickname result["email"] = data_list.email result["description"] = data_list.description result["group"] = data_list.group result["avatar"] = data_list.avatar result["sex"] = data_list.sex result["score"] = data_list.score result["status"] = data_list.status else: nickname = ["菜刀诗人", "SUONGLO", "你是哪块小饼干呐", "-夕凉_", "散漫的Taco", "奥特曼", "渡尘烟", "知意南风", "绿色橘生", "花胖胖", "侬本多情", "情欲孤独", "麦记花"] result = { 'id': '0' , 'username': '' , 'password': '' , 'nickname': random.choice(nickname) , 'email': '' , 'description': '素面朝天浅笑吟,倾国倾城两相宜.' , 'score': 0 , 'group': 0 , 'avatar': "/static/uploads/avatar/{}.png".format(random.randint(1, 10)) , 'sex': 3 , 'status': 1 } return render_template('admin/users/edit.html', top_nav='users', activity_nav='edit', data=result, group_list=group_list_data) else: from_data = request.form from_data = from_data.to_dict() # 是否修改密码 if from_data['password']: from_data['password'] = common.hashPwd(from_data['password']) else: from_data.pop('password') # 不修改密码,删除键值 if "status" in request.form.keys(): from_data['status'] = 1 else: from_data['status'] = 0 if id != 0: models.users.update(from_data) return json.dumps({"code": 0, "msg": "完成!"}) else: checkName = models.users.check_username(from_data['username']) if checkName is None: # 初始化role 并插入数据库 role = models.users( username=from_data['username'], password=from_data['password'], nickname=from_data['nickname'], email=from_data['email'], description=from_data['description'], avatar=from_data['avatar'], sex=from_data['sex'], login_num=0, score=from_data['score'], group=from_data['group'], status=from_data['status'], register_ip='127.0.0.1', birthday='0001-01-01 00:00:00', reg_time=time.strftime('%Y-%m-%d %H:%M:%S'), update_time=time.strftime('%Y-%m-%d %H:%M:%S') ) MysqlDB.session.add(role) MysqlDB.session.flush() MysqlDB.session.commit() return json.dumps({"code": 0, "msg": "完成!"}) else: return json.dumps({"code": 1, "msg": "用户名已存在!"})
def homepage(): output = json.dumps({"api": '1.0'}) return success_handle(output)
def datamaps(): ret_code, msg = verify_request("datamap") user_id = msg.get("user_id") is_valid = msg.get("valid", False) if ret_code != 200: return msg, ret_code if not is_valid: return jsonify({'message': 'User does not have permission'}), 403 if request.method == 'GET': # Get all datamaps try: maps = [] if msg.get("is_admin"): for dm, ac, ow in db.session.query(DataMap, AccessibilityStatus, Owner) \ .filter(DataMap.access_id == AccessibilityStatus.id, DataMap.owner_id == Owner.id).all(): maps.append(dm.to_json(ac.name, ow)) else: # Get all own datamap access_status = "private" for dm, ac, ow in db.session.query(DataMap, AccessibilityStatus, Owner) \ .filter(DataMap.access_id == AccessibilityStatus.id, DataMap.owner_id == Owner.id) \ .filter(Owner.owner_type == OwnerType.USER, Owner.owned_by_user_id == user_id) \ .filter(AccessibilityStatus.name == access_status).all(): maps.append(dm.to_json(ac.name, ow)) # Get all accessible private datamaps owned by farms flist = get_accessible_farm_list(msg) if flist: for dm, ac, ow in db.session.query(DataMap, AccessibilityStatus, Owner) \ .filter(DataMap.access_id == AccessibilityStatus.id, DataMap.owner_id == Owner.id) \ .filter(Owner.owner_type == OwnerType.FARM, Owner.owned_by_farm_id.in_(flist)) \ .filter(AccessibilityStatus.name == access_status).all(): maps.append(dm.to_json(ac.name, ow)) # Public datamap access_status = "public" for dm, ac, ow in db.session.query(DataMap, AccessibilityStatus, Owner) \ .filter(DataMap.access_id == AccessibilityStatus.id, DataMap.owner_id == Owner.id) \ .filter(AccessibilityStatus.name == access_status).all(): maps.append(dm.to_json(ac.name, ow)) if not maps: return jsonify({'message': 'No data map found'}), 404 else: json_str = json.dumps(maps) response = jsonify(json_str) except exc.SQLAlchemyError: return jsonify({'message': 'No data map found'}), 404 elif request.method == "POST": data = request.json farm_id = request.args.get('farm_id') owner = { "owned_by": None, "owner_id": None } if farm_id: owner["owned_by"] = OwnerType.FARM owner["owner_id"] = farm_id else: owner["owned_by"] = OwnerType.USER owner["owner_id"] = user_id response = create_datamap(data, owner) else: return jsonify({'message': 'Method is not supported'}), 404 return response
def saveweather(): data = request.form['result'] print(data) user = mongo.db.users user.insert_one( { 'weather': data } ) return json.dumps({'status':'OK','data':data})
def train(): output = json.dumps({"success": True}) if 'file' not in request.files: print("Face image is required") return error_handle("Face image is required.") else: print("File request", request.files) file = request.files['file'] if file.mimetype not in app.config['file_allowed']: print("File extension is not allowed") return error_handle( "We are only allow upload file with *.png , *.jpg") else: # get name in form data name = request.form['name'] print("Information of that face", name) print("File is allowed and will be saved in ", app.config['storage']) filename = secure_filename(file.filename) trained_storage = path.join(app.config['storage'], 'trained') file.save(path.join(trained_storage, filename)) # let start save file to our storage # save to our sqlite database.db created = int(time.time()) print("time upload ", created) user_id = app.db.insert( 'INSERT INTO users(name, created) values(?,?)', [name, created]) print("user id id ", user_id) # if user_id: # # print("User saved in data", name, user_id) # # user has been save with user_id and now we need save faces table as well # # face_id = app.db.insert('INSERT INTO faces(user_id, filename, created) values(?,?,?)', # [user_id, filename, created]) # # if face_id: # # print("cool face has been saved") # face_data = {"id": face_id, "filename": filename, "created": created} # return_output = json.dumps({"id": user_id, "name": name, "face": [face_data]}) # return success_handle(return_output) # else: # # print("An error saving face image.") # # return error_handle("n error saving face image.") # # else: # print("Something happend") # return error_handle("An error inserting new user") print("Request is contain image") return success_handle(output)
def species(): species = Species.query.all() return Response(json.dumps([s.serialize() for s in species]), status=200, mimetype='application/json')
def error_handle(error_message, status=500, mimetype='application/json'): return Response(json.dumps({"error": { "message": error_message }}), status=status, mimetype=mimetype)
def verify_request(*args, **kwargs): uuid = request.form.get('uuid') what = request.form.get('what') why = request.form.get('why') financial_assistance = request.form.get('financial_assistance', 0) verification_status = request.form.get('verification_status') verified_by = kwargs.get('user_id', 0) r_id = request.form.get('r_id') name = request.form.get('name') where = request.form.get('geoaddress') mob_number = request.form.get('mob_number') urgent_status = request.form.get('urgent', 'no') source = request.form.get('source', 'covidsos') volunteers_reqd = request.form.get('volunteer_count', 1) current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) if (verification_status is None): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Please send verification status' }) if ((r_id is None) or (uuid is None)): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Please send UUID/request ID' }) r_df = request_data_by_uuid(uuid) if (r_df.shape[0] == 0): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Invalid UUID/request ID' }) if (r_df.loc[0, 'source'] != source): response_0 = update_requests_db({'uuid': uuid}, {'source': source}) if (r_df.loc[0, 'status'] == 'received'): r_v_dict = { 'r_id': [r_id], 'why': [why], 'what': [what], 'where': [where], 'verification_status': [verification_status], 'verified_by': [verified_by], 'timestamp': [current_time], 'financial_assistance': [financial_assistance], 'urgent': [urgent_status] } df = pd.DataFrame(r_v_dict) expected_columns = [ 'timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by', 'financial_assistance', 'urgent' ] response_2 = update_requests_db({'uuid': uuid}, { 'status': verification_status, 'volunteers_reqd': volunteers_reqd }) print('updated the status') past_id, past_status = check_past_verification(str(r_id)) if (past_status == True): r_v_dict = { 'r_id': r_id, 'why': why, 'what': what, 'where': where, 'verification_status': verification_status, 'verified_by': verified_by, 'timestamp': current_time, 'financial_assistance': financial_assistance, 'urgent': urgent_status } rv_dict = {x: r_v_dict[x] for x in r_v_dict} update_request_v_db({'id': (past_id)}, rv_dict) else: x, y = add_request_verification_db(df) if (verification_status == 'verified'): #Move to message_templates.py file requestor_text = '[COVIDSOS] Your request has been verified. We will look for volunteers in your neighbourhood.' send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True) message_all_volunteers(uuid, neighbourhood_radius, search_radius) else: #Move to message_templates.py file requestor_text = '[COVIDSOS] Your request has been cancelled/rejected. If you still need help, please submit request again.' send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True) return json.dumps({ 'Response': {}, 'status': response_2['status'], 'string_response': response_2['string_response'] }) else: return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Request already verified/rejected' })
def addRoute(): # Verifies if user is authorized to access route user_check = verify_user(request) if user_check["status"] is False: return Response( response=json.dumps( {"error": "Not authorized to access this page"}), status=401, mimetype="application/json", ) # Setup DB for later functions db = get_db() data = request.get_json() # GET Resources if request.method == "GET": # Fetches all Battlepasses for user's id if request.args.get("type") == "all": my_passes = db.execute("SELECT * FROM userPass WHERE user_id = ?", (user_check["user_id"], )).fetchall() # Maps all battlepasses to a list passes_list = [] for x in my_passes: passes_list.append(list(x)) # Returns response object return Response( response=json.dumps({"passes": passes_list}), status=200, mimetype="application/json", ) # Fetches only requested battlepass via id elif request.args.get("bpid") is not None: my_pass = db.execute("SELECT * FROM userPass WHERE id = ?", (request.args.get("bpid"), )).fetchone() if my_pass is not None: return Response( response=json.dumps({"passes": list(my_pass)}), status=200, mimetype="application/json", ) else: return Response( response=json.dumps({"error": "Battlepass not found"}), status=404, mimetype="application/json", ) else: return Response( response=json.dumps({ "error": "Please include either a type or dbid query parameter" }), status=404, mimetype="application/json", ) # POST Resources elif request.method == "POST": bpName = data["name"] currentXP = data["currentXP"] totalXP = data["totalXP"] endDate = data["endDate"] user_id = user_check["user_id"] # Verifies the user doesn't already have an entry with this name name_check = db.execute( "SELECT endDate FROM userPass WHERE user_id = ? AND bpName = ?", (user_id, bpName), ).fetchone() if name_check is not None: return Response( response=json.dumps({ "message": "You already have a battlepass with this name", "success": False, }), status=400, mimetype="application/json", ) db.execute( "INSERT INTO userPass (user_id, bpName, currentXP, totalXP, endDate) VALUES (?, ?, ?, ?, ?)", ( user_id, bpName, currentXP, totalXP, endDate, ), ) db.commit() return Response( response=json.dumps({ "message": "Added Successfully", "success": True }), status=201, mimetype="application/json", ) # PATCH Resources elif request.method == "PATCH": if ("id" not in data or "name" not in data or "currentXP" not in data or "totalXP" not in data or "endDate" not in data): return Response( response=json.dumps({ "message": "Please include all fields", "success": False }), status=404, mimetype="application/json", ) # Check if BP is owned by user requested_bp = db.execute("SELECT * FROM userPass WHERE id = ?", (data["id"], )).fetchone() if requested_bp["user_id"] != user_check["user_id"]: print(requested_bp["id"]) print(user_check["user_id"]) return Response( response=json.dumps({ "message": "Not Authorized To Edit", "success": False }), status=401, mimetype="application/json", ) db.execute( "UPDATE userPass SET bpName = ?, currentXP = ?, totalXP = ?, endDate = ? WHERE id = ?", ( data["name"], data["currentXP"], data["totalXP"], data["endDate"], data["id"], ), ) db.commit() return jsonify({"message": "Updated Successfully", "success": True}) # DELETE Resources else: # Verifies user included an id if request.args.get("bpid") is None: return jsonify({ "message": "Please include a Battlepass ID", "success": False }), 404 else: # Verifies requested battlepass exists requested_bp = db.execute("SELECT * FROM userPass WHERE id = ?", (request.args.get("bpid"), )).fetchone() if requested_bp is None: return jsonify({ "message": "Battlepass does not exist", "success": False }), 404 # Verifies user owns requested battlepass elif requested_bp["user_id"] != user_check["user_id"]: return jsonify({ "message": "Battlepass does not belong to user", "success": False }), 401 # Deletes battlepass and returns else: db.execute("DELETE from userPass WHERE id = ?", (request.args.get("bpid"), )) db.commit() return jsonify({ "message": "Deleted Successfully", "success": True }), 200
def auto_assign_volunteer(): v_id = request.form.get('volunteer_id') uuid = request.form.get('uuid') matching_by = 'autoassigned' task_action = request.form.get('task_action') r_df = request_data_by_uuid(uuid) v_df = volunteer_data_by_id(v_id) if (r_df.shape[0] == 0): return json.dumps({ 'status': False, 'string_response': 'Request ID does not exist.', 'Response': {} }) if (v_df.shape[0] == 0): return json.dumps({ 'status': False, 'string_response': 'Volunteer does not exist', 'Response': {} }) else: r_id = r_df.loc[0, 'r_id'] if (((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (r_df.loc[0, 'status'] == 'pending')) & (task_action == 'accepted')): current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) req_dict = { 'volunteer_id': [v_id], 'request_id': [r_id], 'matching_by': [matching_by], 'timestamp': [current_time] } df = pd.DataFrame(req_dict) response = request_matching(df) response_2 = update_requests_db({'id': r_id}, {'status': 'matched'}) response_3 = update_nearby_volunteers_db({'r_id': r_id}, {'status': 'expired'}) #Move to message_templates.py file #Send to Volunteer v_sms_text = '[COVID SOS] Thank you agreeing to help. Name:' + r_df.loc[ 0, 'name'] + ' Mob:' + str( r_df.loc[0, 'mob_number']) + ' Request:' + r_df.loc[ 0, 'request'] + ' Address:' + r_df.loc[0, 'geoaddress'] send_sms(v_sms_text, int(v_df.loc[0, 'mob_number']), sms_type='transactional', send=True) #Send to Requestor v_sms_text = '[COVID SOS] Volunteer ' + v_df.loc[ 0, 'name'] + ' will help you. Mob: ' + str( v_df.loc[0, 'mob_number']) send_sms(v_sms_text, int(r_df.loc[0, 'mob_number']), sms_type='transactional', send=True) return json.dumps(response) elif ((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (r_df.loc[0, 'status'] == 'pending')): response_3 = update_nearby_volunteers_db( { 'r_id': r_id, 'v_id': v_id }, {'status': 'expired'}) return json.dumps({ 'status': True, 'string_response': 'Request rejected', 'Response': {} }) else: return json.dumps({ 'status': False, 'string_response': 'Request already assigned', 'Response': {} })
def create_request(): name = request.form.get('name') mob_number = request.form.get('mob_number') email_id = request.form.get('email_id', '') age = request.form.get('age') address = request.form.get('address') geoaddress = request.form.get('geoaddress', address) user_request = request.form.get('request') latitude = request.form.get('latitude', 0.0) longitude = request.form.get('longitude', 0.0) source = request.form.get('source', 'covidsos') status = request.form.get('status', 'received') country = request.form.get('country', 'India') current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) uuid = generate_uuid() req_dict = { 'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id], 'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude], 'longitude': [longitude], 'source': [source], 'age': [age], 'request': [user_request], 'status': [status], 'uuid': [uuid] } df = pd.DataFrame(req_dict) df['email_id'] = df['email_id'].fillna('') expected_columns = [ 'timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude', 'longitude', 'source', 'request', 'age', 'status', 'uuid' ] x, y = add_requests(df) response = {'Response': {}, 'status': x, 'string_response': y} if (x): #Move to message_templates.py file url = "https://wa.me/918618948661?text=" + urllib.parse.quote_plus( 'Hi') sms_text = "[COVIDSOS] " + name + ", we have received your request. We will call you soon. If urgent, please click " + url send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True) # mod_url = "https://wa.me/91"+str(mob_number)+"?text="+urllib.parse.quote_plus('Hey') #Add to message_templates.py mod_url = "https://covidsos.org/verify/" + str(uuid) mod_sms_text = 'New query received. Verify lead by clicking here: ' + mod_url moderator_list = get_moderator_list() for i_number in moderator_list: send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True) #move to async # volunteer_request.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid),countdown=100) #Move to Async after 5 mins # sms_text = "[COVIDSOS] "+name+", you can track your request at "+url # send_sms(sms_text,sms_to=int(mob_number),sms_type='transactional',send=True) #Send SMS to volunteers via async Task: #NEEDS REVIEW # volunteer_sms_countdown = 30 # volunteer_request.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid)) # no_volunteer_assigned.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid),countdown=volunteer_sms_countdown) #Schedule message after 30 mins depending on status - Send WhatsApp Link here. return json.dumps(response)