Try to pass two parameters but seems like I'm missing something with syntax here , can someone help me on this?
#app.route('/BotMetrics/<int:fromdate>/<int:todate>')
def user(fromdate, todate):
print("connecting")
con = Get_hdb()
cursor1 = con.cursor(pymysql.cursors.DictCursor)
cursor1.execute("select * from order_details where date between '%s' and '%s'",(fromdate,todate,))
row = cursor1.fetchall()
resp = jsonify(row)
resp.status_code = 200
return resp
Trying to access URL , here I want to pass two parameters FromDate and ToDate in URL ,
http://127.0.0.1:5000/BotMetrics/?FromDate?Todate
Updated the code to below and it worked
#app.route('/BotMetrics/<fromdate>/<todate>')
def user(fromdate=None, todate=None):
print("connecting")
con = Get_hdb()
cursor1 = con.cursor(pymysql.cursors.DictCursor)
cursor1.execute("select * from order_details where date between %s and %s",(fromdate,todate,))
row = cursor1.fetchall()
resp = jsonify(row)
resp.status_code = 200
return resp
URL
http://127.0.0.1:5000/BotMetrics/2021-02-01/2021-02-27
Related
this is my code
#app.route('/certification', methods=['POST'])
def certificationVector():
# get data from database; it works correctly
if request.is_json:
data = request.get_json()
print(data)
description = data['description']
print("descrrrr", description)
id_certification = data['id_certification']
vector = textToVect(description)
print("vect ", vector)
vector_str = ','.join(map(str, vector))
# id_offer = data['id_offer'],
# update the column certification_vector in table certification
certification_to_update = db.session.query(Certification).filter_by(id=id_certification).first()
print("ppp", certification_to_update.id)
certification_to_update.certification_vector = ''.join(map(str, vector))
print("dbbbbbbbbbbbbbbbbb", certification_to_update.certification_vector)
db.session.commit()
print("zzzzzzzzzzzzzzzzzzzzzzzzzzzz")
response = jsonify(id_certification=certification_to_update.id)
return response
else:
return {"error": "The request payload is not in JSON format"}
this is webhook
. i recive json form api with this . i need extract json tags and send to mysql database . problem is it not sent all json tags . i think it need loop at the step i tag with this step at code . thanks .
import json
import urllib.parse
import urllib.request
import mysql.connector
urls = ('/.*', 'hooks')
app = web.application(urls, globals())
class hooks:
def POST(self):
data = web.data()
print()
print('DATA RECEIVED:')
print(data)
print()
cts = data.decode('utf-8') #decode bytes to string
r1 = cts.replace(cts[:9], '')
parsed = urllib.parse.unquote_plus(r1) # ready for post
print(parsed)
print(cts)
print(type(cts))
myurl = "https://webhook.site/c0e861b0-3cc1-42c2-a0c6-54ad980b01b0"
req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = parsed
jsondataasbytes = jsondata.encode('utf-8') # convert to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
print(jsondataasbytes)
response = urllib.request.urlopen(req, jsondataasbytes)
test_dict = json.loads(parsed)[0]
print(type(test_dict))
# Extracting specific keys from dictionary <<<<<<THIS STEP>>>>>>>>>
indic_label = test_dict['indicator_label']
status = test_dict['status']
creation_date = test_dict['creation_date']
laststatus = test_dict['last_status']
base = test_dict['base_currency']
quote_currency = test_dict['quote_currency']
indic = test_dict['indicator']
prices = test_dict['prices']
mydb = mysql.connector.connect(
host="*",
user="*",
password="*",
database="*"
)
cursor = mydb.cursor()
cursor.execute("""INSERT INTO allcoins
(base,quote_currency , indic,status,laststatus,creation_date,prices,indic_label)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)""",
(base, quote_currency, indic, status, laststatus, creation_date, prices, indic_label))
mydb.commit()
cursor.close()
mydb.close()
return 'OK'
if __name__ == '__main__':
app.run()
you can post test data to this hook by this curl
curl -d "messages=%5B%7B%22values%22%3A+%7B%22momentum%22%3A+%220.00%22%7D%2C+%22exchange%22%3A+%22binance%22%2C+%22market%22%3A+%22BNT%2FETH%22%2C+%22base_currency%22%3A+%22BNT%22%2C+%22quote_currency%22%3A+%22ETH%22%2C+%22indicator%22%3A+%22momentum%22%2C+%22indicator_number%22%3A+0%2C+%22analysis%22%3A+%7B%22config%22%3A+%7B%22enabled%22%3A+true%2C+%22alert_enabled%22%3A+true%2C+%22alert_frequency%22%3A+%22once%22%2C+%22signal%22%3A+%5B%22momentum%22%5D%2C+%22hot%22%3A+0%2C+%22cold%22%3A+0%2C+%22candle_period%22%3A+%224h%22%2C+%22period_count%22%3A+10%7D%2C+%22status%22%3A+%22hot%22%7D%2C+%22status%22%3A+%22hot%22%2C+%22last_status%22%3A+%22hot%22%2C+%22prices%22%3A+%22+Open%3A+0.000989+High%3A+0.000998+Low%3A+0.000980+Close%3A+0.000998%22%2C+%22lrsi%22%3A+%22%22%2C+%22creation_date%22%3A+%222020-05-10+16%3A16%3A23%22%2C+%22hot_cold_label%22%3A+%22%22%2C+%22indicator_label%22%3A+%22%22%2C+%22price_value%22%3A+%7B%22open%22%3A+0.000989%2C+%22high%22%3A+0.000998%2C+%22low%22%3A+0.00098%2C+%22close%22%3A+0.000998%7D%2C+%22decimal_format%22%3A+%22%25.6f%22%7D%2C+%7B%22values%22%3A+%7B%22leading_span_a%22%3A+%220.00%22%2C+%22leading_span_b%22%3A+%220.00%22%7D%2C+%22exchange%22%3A+%22binance%22%2C+%22market%22%3A+%22BNT%2FETH%22%2C+%22base_currency%22%3A+%22BNT%22%2C+%22quote_currency%22%3A+%22ETH%22%2C+%22indicator%22%3A+%22ichimoku%22%2C+%22indicator_number%22%3A+1%2C+%22analysis%22%3A+%7B%22config%22%3A+%7B%22enabled%22%3A+true%2C+%22alert_enabled%22%3A+true%2C+%22alert_frequency%22%3A+%22once%22%2C+%22signal%22%3A+%5B%22leading_span_a%22%2C+%22leading_span_b%22%5D%2C+%22hot%22%3A+true%2C+%22cold%22%3A+true%2C+%22candle_period%22%3A+%224h%22%2C+%22hot_label%22%3A+%22Bullish+Alert%22%2C+%22cold_label%22%3A+%22Bearish+Alert%22%2C+%22indicator_label%22%3A+%22ICHIMOKU+4+hr%22%2C+%22mute_cold%22%3A+false%7D%2C+%22status%22%3A+%22cold%22%7D%2C+%22status%22%3A+%22cold%22%2C+%22last_status%22%3A+%22cold%22%2C+%22prices%22%3A+%22+Open%3A+0.000989+High%3A+0.000998+Low%3A+0.000980+Close%3A+0.000998%22%2C+%22lrsi%22%3A+%22%22%2C+%22creation_date%22%3A+%222020-05-10+16%3A16%3A23%22%2C+%22hot_cold_label%22%3A+%22Bearish+Alert%22%2C+%22indicator_label%22%3A+%22ICHIMOKU+4+hr%22%2C+%22price_value%22%3A+%7B%22open%22%3A+0.000989%2C+%22high%22%3A+0.000998%2C+%22low%22%3A+0.00098%2C+%22close%22%3A+0.000998%7D%2C+%22decimal_format%22%3A+%22%25.6f%22%7D%2C+%7B%22values%22%3A+%7B%22bbp%22%3A+%220.96%22%2C+%22mfi%22%3A+%2298.05%22%7D%2C+%22exchange%22%3A+%22binance%22%2C+%22market%22%3A+%22BNT%2FETH%22%2C+%22base_currency%22%3A+%22BNT%22%2C+%22quote_currency%22%3A+%22ETH%22%2C+%22indicator%22%3A+%22bbp%22%2C+%22indicator_number%22%3A+1%2C+%22analysis%22%3A+%7B%22config%22%3A+%7B%22enabled%22%3A+true%2C+%22alert_enabled%22%3A+true%2C+%22alert_frequency%22%3A+%22once%22%2C+%22candle_period%22%3A+%224h%22%2C+%22period_count%22%3A+20%2C+%22hot%22%3A+0.09%2C+%22cold%22%3A+0.8%2C+%22std_dev%22%3A+2%2C+%22signal%22%3A+%5B%22bbp%22%2C+%22mfi%22%5D%2C+%22hot_label%22%3A+%22Lower+Band%22%2C+%22cold_label%22%3A+%22Upper+Band+BB%22%2C+%22indicator_label%22%3A+%22Bollinger+4+hr%22%2C+%22mute_cold%22%3A+false%7D%2C+%22status%22%3A+%22cold%22%7D%2C+%22status%22%3A+%22cold%22%2C+%22last_status%22%3A+%22cold%22%2C+%22prices%22%3A+%22+Open%3A+0.000989+High%3A+0.000998+Low%3A+0.000980+Close%3A+0.000998%22%2C+%22lrsi%22%3A+%22%22%2C+%22creation_date%22%3A+%222020-05-10+16%3A16%3A23%22%2C+%22hot_cold_label%22%3A+%22Upper+Band+BB%22%2C+%22indicator_label%22%3A+%22Bollinger+4+hr%22%2C+%22price_value%22%3A+%7B%22open%22%3A+0.000989%2C+%22high%22%3A+0.000998%2C+%22low%22%3A+0.00098%2C+%22close%22%3A+0.000998%7D%2C+%22decimal_format%22%3A+%22%25.6f%22%7D%5D" -X POST http://192.168.30.1
Perhaps define all variables upfront because you still need them to write to the db, then check if they are in the response and update:
indic_label = ''
status = ''
creation_date = ''
laststatus = ''
base = ''
quote_currency = ''
indic =''
prices = ''
if test_dict['indicator_label']:
indic_label = test_dict['indicator_label']
if test_dict['status']:
status = test_dict['status']
...
...
If it's an all or none situation, you can check for one variable then exit, otherwise check for each of them.
I suspect it has something got to do with refresh token. Could not understand how to use it by the docs. Can I know the exact code how to use it?
The access token is created during login:
#app.route('/login', methods=['POST','GET'])
def login():
username = request.form["email"]
password = request.form["password"]
my_token_expiry_time = datetime.timedelta(seconds=60)
segments = 0
access_token = None
if request.method == 'POST':
result_set = authenticate_user(username, password)
if result_set:
ss1 = select([nsettings]).\
where(nsettings.c.mattribute == 'my_jwt_expiry_time_min')
rss1 = g.conn.execute(ss1)
if rss1.rowcount > 0:
for r in rss1:
my_token_expiry_time = datetime.timedelta(seconds=
(int(r[nsettings.c.mvalue])* 60))
else:
my_token_expiry_time = datetime.timedelta(
seconds=(2 * 60 *60)) # 2 hours
#print result_set, 'result_set result_set'
session['email'] = result_set['email']
access_token = create_access_token(
identity=username, expires_delta=my_token_expiry_time)
user_dict = result_set
if user_dict:
session['email'] = user_dict['email']
session['id'] = result_set['id']
# users and related views
session['access_token'] = access_token
print access_token, 'aaaaaaaaaaa'
return jsonify({
'email': session['email'],
'user_id': result_set['id'],
'access_token': access_token,
'id': session['id'],
}), 200
else:
return jsonify({'message': "Invalid credentials, retry"}), 401
return "True"
The flask api call to upload:
#app.route('/rt/api/v1.0/issues/<int:issue_id>/documents', methods=['POST'])
#jwt_required
def rt_doc_upload(issue_id):
'''
Upload documents for a rt ticket.
'''
# Iterate through the list of files, we don't care about the
# attribute name. We consider only the first file and ignore the
# rest.
if 'id' in session:
uploader = "3"
minternal_only = True
bool_internal_update = False
msg_str = None
for attr, document in request.files.iteritems():
trans = g.conn.begin()
try:
orig_filename = document.filename
filename, upload_folder = check_or_insert_document(
orig_filename, uploader)
new_doc = add_doc(orig_filename, filename)
print orig_filename, 'origooooo'
ins = archival_docs.insert().values(new_doc)
rs = g.conn.execute(ins)
doc_id = rs.inserted_primary_key[0]
filename = (str(doc_id) + '_' + orig_filename)
stmt = archival_docs.update().values(stored_name=filename).\
where(archival_docs.c.id == doc_id)
g.conn.execute(stmt)
document.save(os.path.join(upload_folder, filename))
mattach_doc_id = genUrl(doc_id)
trans.commit()
return jsonify(
{'issue_doc_id': rs.inserted_primary_key[0]}), 201
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Did not find any file"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
When used with runserver and on commenting the jwt_required decorator I am able to upload and download files
Using sqlalchemy core, python and flask. The api call to upload worked for more than a month, but suddenly stopped working now
I want to create a HTTP link from db info. such as ip and port number, somehow i tried this but keep getting a error cant parse and port hope any one can help me out
#app.route('/link_test/<string:id>')
#is_logged_in
def link_test(id):
#Create cursor
cur = mysql.get_db().cursor()
#get item by itemno
result = cur.execute("SELECT * FROM testlist WHERE id = %s", [id])
doc = cur.fetchone()
)
doc = {"id": test[0], "rdno": test[1], "ipno": test[2], "port": test[3]}
cur.close()
ipno = test['ipno']
port = test['port']
url_uptime = 'https://<string:ipno>:<string:port>/stats/uptime/'
return render_template('link_test.html', uptime=json.loads(r_uptime))
<string:ipno>:<string:port> is a Flask path, not something to be literally used as a URL
If you wanted to create this string, it's called formatting, not parsing
ipno = doc['ipno']
port = doc['port']
url_uptime = 'https://{}:{}/stats/uptime/'.format(ipno, port)
r_uptime = requests.get(url_uptime, verify=False).content
You'll also want to define test somewhere before doc is created
getVars1 = doc[2]
url='/stats/uptime/'
url_uptime = ('https://'+getVars1+url)
great thanks mate
I am trying to hit an API, and get data with requests module in python.
I am using conn.request("POST", "/middleware/application/servicegateway/Publicis/XXX/calculatetax", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
This does print the response as {"base_amount":40,"tax_percent":0.05,"total_tax":1.90476}
But, when I try to put this response data into a variable,using
I get the error as,
RemoteDisconnected: Remote end closed connection without response
Complete code is as below :
def create_query (start_date, end_date):
raw_query1 = "Select cnsmr_id as cnsmr_id_1, cnsmr_loc_id as loc_id_1 from staging.trvs_cnsmr where registration_date between '%s' and '%s' " %(start_date, end_date)
red_engine = create_engine('redshift+psycopg2://YYYY:ZZZZZ#AA.BB.CC.DD:5000/DB')
test1 = pd.read_sql_query(raw_query1,red_engine)
for index1, row1 in test1.iterrows():
print(row1['cnsmr_id_1'], row1['loc_id_1'])
raw_query2 = "Select cnsmr_loc_id, state, cnsmr_loc_addrss_line_1, cnsmr_loc_addrss_line_2, city, country, zipcode from staging.trvs_consumer_loc1 where cnsmr_loc_id = '%s' and country = 'CAN ' " %(row1['loc_id_1'])
test2 = pd.read_sql_query(raw_query2,red_engine)
for index2, row2 in test2.iterrows():
print(row2['cnsmr_loc_id'], row2['state'], row2['cnsmr_loc_addrss_line_1'], row2['cnsmr_loc_addrss_line_2'], row2['city'], row2['country'], row2['zipcode'] )
raw_query3 = "Select subscription_id, cnsmr_id as cnsmr_id_2 , bus_id, payment_amount from staging.trvs_cnsmr_payment where cnsmr_id_2 = '%s' " %(row1['cnsmr_id_1'])
test3 = pd.read_sql_query(raw_query3,red_engine)
for index3, row3 in test3.iterrows():
print (row3['bus_id'], row3['payment_amount'], row3['subscription_id'], row3['cnsmr_id_2'], row2['zipcode'])
payload = "{\n\"businessunit\":\"%s\", \"amount\":\"%d\", \"addresslineone\":\"%s\", \"addresslinetwo\":\"%s\", \"stateorprovince\":\"%s\", \"postcalcode\":\"%s\", \"city\":\"%s\", \"country\":\"%s\"\n}" %(row3['bus_id'], row3['payment_amount'], row2['cnsmr_loc_addrss_line_1'], row2['cnsmr_loc_addrss_line_2'], row2['state'], row2['zipcode'], row2['city'], row2['country'])
headers = {"X-API-CLIENT-ID":"XXXX", "X-API-TOKEN":"5a98"}
conn.request("POST", "/application/servicegateway/client/atn/taxation/calculatetax", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
x = data.decode("utf-8")