def Final_checkout(): if request.method == 'GET': flash("Access denied !") return redirect('/') if 'loggedin' in session and session['username'] == "pharmacist": idk = request.form['pid'] medid = request.form['mediname'] jo = {} Quantity = request.form['Quantity'] cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicines_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData) jo = [] cur1 = mysql.connection.cursor() cur1.execute("SELECT * FROM medicine WHERE patient_id LIKE %s", [idk]) fetchedData1 = cur1.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medi1 = d.decode(fetchedData1) cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicines_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() data = d.decode(fetchedData) ji = [] for i in medi1: for j in data: if (i["medicine_name"] == j["medicine_name"]): i["rate"] = j["rate"] ji.append(i) cur2 = mysql.connection.cursor() cur2.execute("SELECT * FROM patient WHERE patient_id LIKE %s", [idk]) userdata = cur2.fetchone() for j in medicaldata: if j['medicine_id'] == int(medid): j['Quantity'] = int(Quantity) jo.append(j) session['tempmedi'] = session['tempmedi'] + jo return render_template('issue_medicines.html', mess=userdata, medi=ji, tempmedi=session['tempmedi']) else: flash("Access denied !") return redirect('/')
def verifyToken(token, mustBeAdmin): if token is None: return None, None tokenB = base64.b64decode(token) tokenS = tokenB.decode("utf-8") tokenJS = json.JSONDecoder().decode(tokenS) id2 = tokenJS["id"] nowS = tokenJS["now"] sharedkey = id2sharedKey.get(id2) if sharedkey is None: return None, None username = id2username.get(id2) if username is None: return None, None if mustBeAdmin and username != "admin": return None, None nowEnc = base64.b64decode(tokenJS["nowEnc"]) ivS = tokenJS["iv"] ivB = base64.b64decode(ivS) aesAlg = algorithms.AES(sharedkey) cipher = Cipher(aesAlg, modes.CBC(ivB)) decryptor = cipher.decryptor() nowDecB = decryptor.update(nowEnc) + decryptor.finalize() unpadder = PKCS7(128).unpadder() nowDecB = unpadder.update(nowDecB) + unpadder.finalize() nowDecS = nowDecB.decode("utf-8") if nowS != nowDecS: # so sharedKey was not working return None, None now = datetime.utcnow() clntNow = datetime.utcfromtimestamp(int(nowS) / 1000) diff = int((now - clntNow).total_seconds()) if -600 < diff < 600: # clntNow within 10 minutes before or after now return expiration(id2), username return None, None
def commitsBehind(): """Calculate how many commits are missing""" url = 'https://api.github.com/repos/%s/maraschino/compare/%s...%s' % ( user, maraschino.CURRENT_COMMIT, maraschino.LATEST_COMMIT) result = urllib2.urlopen(url).read() git = json.JSONDecoder().decode(result) return git['total_commits']
def latestCommit(): """Get SHA hash from latest commit""" url = 'https://api.github.com/repos/%s/maraschino/commits/%s' % (user, branch) result = urllib2.urlopen(url).read() git = json.JSONDecoder().decode(result) return git['sha']
def couchpotato_api(method, params=None, use_json=True, dev=False): username = get_setting_value('couchpotato_user') password = get_setting_value('couchpotato_password') if params: params = '/?%s' % params else: params = '/' params = (params).replace(' ', '%20') url = '%s/%s%s' % (couchpotato_url(), method, params) req = urllib2.Request(url) if username and password: base64string = base64.encodestring( '%s:%s' % (username, password)).replace('\n', '') req.add_header("Authorization", "Basic %s" % base64string) data = urllib2.urlopen(req).read() if dev: print url print data if use_json: data = json.JSONDecoder().decode(data) return data
def create_bot_from_json(json_str): decoded = json.JSONDecoder().decode(json_str) url = decoded['url'] updates = [Message(message=upd) for upd in decoded['updates']] last_upd_id = decoded['last_upd_id'] return ControlBot(url=url, updates=updates, last_upd_id=last_upd_id)
def _default(self, obj): """ return a serialized version of obj or raise a TypeError :param obj: :return: Serialized version of obj """ return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)
def check_and_decode_json(update_json): updates = json.JSONDecoder().decode(update_json) if updates['ok']: result = take_messages_from_updates(updates['result']) else: result = None return result
def Final_checkout_diagnostics(): if request.method == 'GET': flash("Access denied !") return redirect('/') idk = request.form['pid'] medid = request.form['mediname'] cur = mysql.connection.cursor() cur.execute("SELECT * FROM diagnostics_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData) jo = [] cur1 = mysql.connection.cursor() cur1.execute("SELECT * FROM diognostics WHERE patient_id LIKE %s", [idk]) fetchedData1 = cur1.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medi1 = d.decode(fetchedData1) ji = [] for i in medi1: for j in medicaldata: if (i["diagnosis"] == j["test_name"]): ji.append(j) session['tempmedi'] = session['tempmedi'] + jo cur2 = mysql.connection.cursor() cur2.execute("SELECT * FROM patient WHERE patient_id LIKE %s", [idk]) userdata = cur2.fetchone() for j in medicaldata: if j['test_id'] == int(medid): jo.append(j) session['tempmedi'] = session['tempmedi'] + jo if 'loggedin' in session and session["username"] == "diagnostic": return render_template('diagonstics.html', mess=userdata, medi=ji, tempmedi=session['tempmedi']) else: flash("Access denied !") return redirect('/')
def xhr_trakt_add_to_list(): media = json.JSONDecoder().decode(request.form['media']) list = json.JSONDecoder().decode(request.form['list']) exist = request.form['exist'] if exist == 'false': logger.log( 'TRAKT :: Creating new custom list: %s' % (list[0]['value']), 'INFO') url = 'http://api.trakt.tv/lists/add/%s' % trakt_apikey() list_params = {} for item in list: if item['value'] == '0': item['value'] = False elif item['value'] == '1': item['value'] == True list_params[item['name']] = item['value'] list = list_params try: trakt = trak_api(url, list) except Exception as e: trakt_exception(e) return jsonify(status='Failed to add %s to %s\n%s' % (media['title'], list['name'], e)) list['slug'] = list['name'].replace(' ', '-') logger.log('TRAKT :: Adding %s to %s' % (media['title'], list['name']), 'INFO') url = 'http://api.trakt.tv/lists/items/add/%s' % (trakt_apikey()) params = {'slug': list['slug'], 'items': [media]} try: trakt = trak_api(url, params) except Exception as e: trakt_exception(e) return jsonify(status='Failed to add %s to %s\n%s' % (media['title'], list['name'], e)) if trakt['status'] == 'success': return jsonify(status='successful') else: return jsonify(status='Failed to add %s to %s' % (media['title'], list['name']))
def get_order_from_db_row(db_row): decoder = json.JSONDecoder() order = Order(db_row[0], db_row[1], db_row[2], decoder.decode(db_row[3])) order.is_complete = bool(db_row[4]) order.courier_id = db_row[5] order.delivery_time = db_row[6] order.delivery_id = db_row[7] return order
def fanarttv_api(url, dev=False): request = urllib2.Request(url) data = urllib2.urlopen(request).read() data = json.JSONDecoder().decode(data) if dev: print url print json.dumps(data, sort_keys=True, indent=4) return data
def __init__(self, server, port): self.http_header = { "Cache-Control": "no-cache", "User-Agent": "DockerRegistryUI", "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } self.jsonde = json.JSONDecoder() self.jsonen = json.JSONEncoder() self.server = server self.port = port
def send_message(self, message): data = message.message_response() try: status = requests.post(self.url + "sendMessage", json=data) decoded_status = json.JSONDecoder().decode( status.content.decode('utf-8')) if not decoded_status.get('ok'): logging.error('Sending error', filename='log.txt') raise SendingError except requests.ConnectionError: logging.error('Connection error (loading updates)', filename='log.txt') raise ConnectionError
def auth(loginOrSignon): try: login = loginOrSignon == "login" data = request.json id2 = data["id"] encData = base64.b64decode(data["ctxt"]) iv = base64.b64decode(data["iv"]) sharedkey = id2sharedKey[id2] aesAlg = algorithms.AES(sharedkey) cipher = Cipher(aesAlg, modes.CBC(iv)) decryptor = cipher.decryptor() decDataDec = decryptor.update(encData) + decryptor.finalize() unpadder = PKCS7(128).unpadder() decDataB = unpadder.update(decDataDec) + unpadder.finalize() decDataS = decDataB.decode("utf-8") credMsgJS = json.JSONDecoder().decode(decDataS) digest = Hash(SHA256()) emailS = credMsgJS["email"] concatS = credMsgJS["password"] + ":" + emailS concatB = concatS.encode("utf-8") digest.update(concatB) concatHash = digest.finalize() (username, storedHash) = userFromDB(emailS) if storedHash is None or storedHash != concatHash: if login: resp = jsonify({"Auth error": "unknown user or bad password"}) resp.status_code = http.HTTPStatus.UNAUTHORIZED return resp else: username2 = credMsgJS["username"] if dbContainsUsername(username2): resp = jsonify({"Auth error": "user name already in use"}) resp.status_code = http.HTTPStatus.UNAUTHORIZED return resp userToDB(emailS, username2, concatHash) username = username2 else: if not login: username2 = credMsgJS["username"] if username != username2: resp = jsonify({"Auth error": "user name can not be changed"}) resp.status_code = http.HTTPStatus.UNAUTHORIZED return resp id2loginDate[id2] = datetime.now() id2username[id2] = username return jsonify({"id": id2, "username": username}) except Exception as ex: resp = jsonify({"error": str(ex)}) resp.status_code = 401 return resp
def tmdb_api(id, param='', dev=False): url = 'http://api.themoviedb.org/3/movie/' + id url += param url += '?api_key=' + tmdb_apikey request = urllib2.Request(url) request.add_header("Accept", "application/json") data = urllib2.urlopen(request).read() data = json.JSONDecoder().decode(data) if dev: print url print json.dumps(data, sort_keys=True, indent=4) return data
def zzal_make_post(): gif_title = request.form.get('gif_title') gif_tag = request.form.get('gif_tag') duration = float(request.form.get('duration')) #float 형변환 ll = request.form.get('url_list') url_list = [] if ll != None: url_list = json.JSONDecoder().decode(request.form.get('url_list')) file_list = request.files.getlist("upload_image") seq_list = json.JSONDecoder().decode(request.form.get('seq_list')) if gif_title == None and gif_tag == None and duration == None and seq_list == None: return 'parm error' if len(seq_list) != len(url_list) + len(file_list): print(seq_list) print(url_list) print(file_list) return 'file, url error' print(gif_title, gif_tag, duration, url_list, file_list, seq_list) url_idx = 0 file_idx = 0 gif = convert_gif.ConvGIF() for seq in seq_list: if seq == 'file': gif.SetFile(file_list[file_idx].stream.read()) file_idx += 1 elif seq == 'url': gif.SetURL(url_list[url_idx]) url_idx += 1 path = gif.Convert(gif_title, duration) if path == None: return 'error' # gif_tag 레디스 등록 db.reg_image(USER_ID, gif_tag, path, gif_title, 'user make', 0, 0) return path
def sickrage_api(params=None, use_json=True, dev=False): username = get_setting_value('sickrage_user') password = get_setting_value('sickrage_password') url = sickrage_url() + params r = urllib2.Request(url) if username and password: base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') r.add_header("Authorization", "Basic %s" % base64string) data = urllib2.urlopen(r).read() if dev: print url print data if use_json: data = json.JSONDecoder().decode(data) return data
def trak_api(url, params={}, dev=False): username = get_setting_value('trakt_username') password = hashlib.sha1(get_setting_value('trakt_password')).hexdigest() params = json.JSONEncoder().encode(params) request = urllib2.Request(url, params) base64string = base64.encodestring('%s:%s' % (username, password)).replace( '\n', '') request.add_header("Authorization", "Basic %s" % base64string) response = urllib2.urlopen(request) response = response.read() response = json.JSONDecoder().decode(response) if dev: print url print json.dumps(response, sort_keys=True, indent=4) return response
def headphones_api(command, use_json=True, dev=False): username = get_setting_value('headphones_user') password = get_setting_value('headphones_password') apikey = get_setting_value('headphones_api') url = '%s/api?apikey=%s&cmd=%s' % (headphones_url(), apikey, command) request = urllib2.Request(url) base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) data = urllib2.urlopen(request).read() if use_json: data = json.JSONDecoder().decode(data) if dev: print 'DEVELOPER :: %s' % url print 'DEVELOPER :: %s' % data return data
from flask import Flask, jsonify, json, abort, request import urllib.request app = Flask(__name__) print("Carregando dados do json em memoria") json_de_imoveis = urllib.request.urlopen( "https://raw.githubusercontent.com/VivaReal/code-challenge/master/properties.json" ).read().decode('utf-8') json_de_imoveis = json.JSONDecoder().decode(json_de_imoveis) json_de_bairros = urllib.request.urlopen( "https://raw.githubusercontent.com/VivaReal/code-challenge/master/provinces.json" ).read().decode('utf-8') json_de_bairros = json.JSONDecoder().decode(json_de_bairros) @app.route('/properties/', methods=['POST']) def properties_create(): json_de_dados = request.json if not all(keys in json_de_dados for keys in ('beds', 'baths', 'x', 'y', 'title', 'price', 'description', 'squareMeters')): abort(400) if json_de_dados['baths'] < 1 or json_de_dados['baths'] > 4: abort(400) if json_de_dados['beds'] < 1 or json_de_dados['beds'] > 5: abort(400)
def get_courier_from_db_row(db_row): decoder = json.JSONDecoder() return Courier(db_row[0], db_row[1], decoder.decode(db_row[2]), decoder.decode(db_row[3]))
def getuserdata(): if request.method == 'GET': flash("Access denied !") return redirect('/') if 'loggedin' in session: session['tempmedi'] = [] ssid = request.form['ssid'] pageinfo = request.form['pageinfo'] cur = mysql.connection.cursor() cur.execute( "SELECT * FROM patient WHERE patient_id LIKE %s and status='Active'", [ssid]) userdata = cur.fetchone() if pageinfo == "update": if userdata: return render_template('update.html', mess=userdata) else: flash('Not Found') return redirect(url_for('Patient_Update')) elif pageinfo == "delete": if userdata: return render_template('delete.html', mess=userdata) else: flash('Not Found') return redirect(url_for('Patient_Delete')) elif pageinfo == "search": if userdata: return render_template('searchpatient.html', mess=userdata) else: flash('Not Found') return redirect(url_for('Patient_Search')) elif pageinfo == "pharmacy": if userdata: cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicine WHERE patient_id LIKE %s ", [ssid]) fetchedData1 = cur.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData1) cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicines_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() data = d.decode(fetchedData) jo = [] for i in medicaldata: for j in data: if (i["medicine_name"] == j["medicine_name"]): i["rate"] = j["rate"] jo.append(i) print(jo) return render_template('issue_medicines.html', mess=userdata, medi=jo, tempmedi="") else: flash('Not Found') return redirect(url_for('Pharmacy')) elif pageinfo == "diagonastics": if userdata: cur = mysql.connection.cursor() cur.execute( "SELECT * FROM diognostics WHERE patient_id LIKE %s", [ssid]) fetchedData1 = cur.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData1) cur = mysql.connection.cursor() cur.execute("SELECT * FROM diagnostics_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() data = d.decode(fetchedData) jo = [] for i in medicaldata: for j in data: if (i["diagnosis"] == j["test_name"]): jo.append(j) return render_template('diagonstics.html', mess=userdata, medi=jo, tempmedi="") else: flash('Not Found') return redirect(url_for('Diagnostics')) elif pageinfo == "billing": if userdata: total_medicine = 0 total_diagnostic = 0 patient_pay = 0 to = datetime.now() day = to.strftime("%Y-%m-%d") stay = to - datetime.strptime(userdata['admission_date'], '%Y-%m-%d') count = int(stay.days) if (userdata['bed_type'] == "General ward"): patient_pay = count * 2000 elif (userdata['bed_type'] == "Semi sharing"): patient_pay = count * 4000 else: patient_pay = count * 8000 cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicine WHERE patient_id LIKE %s", [ssid]) fetchedData1 = cur.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData1) cur = mysql.connection.cursor() cur.execute("SELECT * FROM medicines_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() data = d.decode(fetchedData) jo = [] for i in medicaldata: for j in data: if (i["medicine_name"] == j["medicine_name"]): i["rate"] = j["rate"] total_medicine += i['rate'] * i["quantity"] jo.append(i) cur = mysql.connection.cursor() cur.execute( "SELECT * FROM diognostics WHERE patient_id LIKE %s", [ssid]) fetchedData1 = cur.fetchall() fetchedData1 = json.dumps(fetchedData1) #create a json decoder d = json.JSONDecoder() medicaldata = d.decode(fetchedData1) cur = mysql.connection.cursor() cur.execute("SELECT * FROM diagnostics_master") fetchedData = cur.fetchall() fetchedData = json.dumps(fetchedData) #create a json decoder d = json.JSONDecoder() data = d.decode(fetchedData) joi = [] for i in medicaldata: for j in data: if (i["diagnosis"] == j["test_name"]): total_diagnostic += j['rate'] joi.append(j) return render_template('finalbilling.html', mess=userdata, medi=jo, tempmedi=joi, date=day, total_medicine=total_medicine, total_diagnostic=total_diagnostic, patient_pay=patient_pay, patient_date=count) else: flash('Not Found') return redirect(url_for('Bill')) else: flash("Access denied !") return redirect('/')