I want to capture the sensor data through thingspeak.
I used the url provided with the api key in the browser:
http://api.thingspeak.com/update?key=MYKEY&field1=25&field2=75
I expect it will return field1 and field2, but the result below shows only the value of field1.
"channel":{
"id":202242,
"name":"DHT11",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Temperature ( degC ) 1",
"field2":"Humidity ( % )",
"created_at":"2016-12-11T17:16:21Z",
"updated_at":"2016-12-11T18:12:00Z",
"last_entry_id":12
},
"feeds":[
{
"created_at":"2016-12-11T18:12:00Z",
"entry_id":12,
"field1":25
}
]
What step have I missed?
Try this approach:
Here you make request using APIs. You will find various API requests here.
import urllib2
import json
import time
READ_API_KEY=' '
CHANNEL_ID= ' '
while True:
TS = urllib2.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
% (CHANNEL_ID,READ_API_KEY))
response = TS.read()
data=json.loads(response)
a = data['created_at']
b = data['field1']
c = data['field2']
d = data['field3']
print a + " " + b + " " + c + " " + d
time.sleep(5)
TS.close()
Related
I encountered a problem when trying to send sms using the SMSC service in Django project.
My Celery task for sending email and sms:
def order_created_retail(order_id):
# Task to send an email when an order is successfully created
order = OrderRetail.objects.get(id=order_id)
subject = 'Order №{}.'.format(order_id)
message_mail = 'Hello, {}! You have successfully placed an order{}. Manager will contact you shortly'.format(order.first_name, order.id)
message_sms = 'Your order №{} is accepted! Wait for operator call'
mail_sent = send_mail(
subject,
message_mail,
'email#email.com',
[order.email]
)
smsc = SMSC()
sms_sent = smsc.send_sms(
[order.phone],
str(message_sms)
)
return mail_sent, sms_sent
Email sends correctly, but for sms I get that error:
Task orders.tasks.order_created_retail[f05458b1-65e8-493b-9069-fbaa55083e7a] raised unexpected: TypeError('quote_from_bytes() expected bytes')
function from SMSC library:
def send_sms(self, phones, message, translit=0, time="", id=0, format=0, sender=False, query=""):
formats = ["flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1", "mms=1", "mail=1", "call=1", "viber=1", "soc=1"]
m = self._smsc_send_cmd("send", "cost=3&phones=" + quote(phones) + "&mes=" + quote(message) + \
"&translit=" + str(translit) + "&id=" + str(id) + ifs(format > 0, "&" + formats[format-1], "") + \
ifs(sender == False, "", "&sender=" + quote(str(sender))) + \
ifs(time, "&time=" + quote(time), "") + ifs(query, "&" + query, ""))
# (id, cnt, cost, balance) или (id, -error)
if SMSC_DEBUG:
if m[1] > "0":
print("Сообщение отправлено успешно. ID: " + m[0] + ", всего SMS: " + m[1] + ", стоимость: " + m[2] + ", баланс: " + m[3])
else:
print("Ошибка №" + m[1][1:] + ifs(m[0] > "0", ", ID: " + m[0], ""))
return m
What am I doing wrong?
Thanks!
to solve this problem, I started investigating the functions that were giving out the error.
It turned out that I was passing an incorrect value. the function was expecting a string. And it took me a long time to figure out why editing didn't help.
It turns out that you have to RESET CELERY every time you make an edit.
I am trying to create a JSON string that I can send in a PUT request but build it dynamically. For example, once I am done, I'd like the string to look like this:
{
"request-id": 1045058,
"db-connections":
[
{
"db-name":"Sales",
"table-name":"customer"
}
]
}
I'd like to use constants for the keys, for example, for request-id, I'd like to use CONST_REQUEST_ID. So the keys will be,
CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"
The values for the keys will be taken from various variables. For example we can take value "Sales" from a var called dbname with the value "Sales".
I have tried json.load and getting exception.
Help would be appreciated please as I am a bit new to Python.
Create a normal python dictionary, then convert it to JSON.
raw_data = {
CONST_DB_NAME: getDbNameValue()
}
# ...
json_data = json.dumps(raw_data)
# Use json_data in your PUT request.
You can concat the string using + with variables.
CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"
request_id = "1045058"
db_name = "Sales"
table_name = 'customer'
json_string = '{' + \
'"' + CONST_REQUEST_ID + '": ' + request_id \
+ ',' + \
'"db-connections":' \
+ '[' \
+ '{' \
+ '"' + CONST_DB_NAME +'":"' + db_name + '",' \
+ '"' + CONST_TABLE_NAME + '":"' + table_name + '"' \
+ '}' \
+ ']' \
+ '}'
print json_string
And this is the result
python st_ans.py
{"request-id": 1045058,"db-connections":[{"db-name":"Sales","table-name":"customer"}]}
I want to integrate PayTR payment gateway with odoo10. I followed the PayTR's developers guide and found a sample codes php script in it. After converting php script to python script, I am getting the error:
ALPN, server did not agree to a protocol
Here are the logs:
logs
Below is the piece of code:
#http.route('/my/payment', type='http', auth="user", website=True)
def pay_now(self, **kw):
partner = request.env.user.partner_id
res = request.env['account.payment'].sudo().search([('partner_id' , '=', partner.id)])
print res
acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'paytr')])
merchant_id = acquirer.paytr_seller_account
merchant_key = acquirer.paytr_merchant_key
merchant_salt = acquirer.paytr_merchant_salt
email = acquirer.paytr_email_account
payment_amount = 300 #example
merchant_oid = "50" #example
merchant_ok_url = "http://www.example.com/success.php"
merchant_fail_url = "http://www.example.com/error.php"
user_basket = "sample product" #example
user_basket = base64.b64encode(bytes(user_basket).encode('utf-8'))
user_ip = get('https://api.ipify.org').text
print user_ip
timeout_limit = "30"
debug_on = 1
test_mode = 0
no_installment = 0
max_installment = 0
currency = "TL"
hash_str = str(merchant_id) + str(user_ip) + str(merchant_oid) + str(email) + str(payment_amount) + str(user_basket) + str(no_installment) + str(max_installment) + str(currency) + str(test_mode)
print hash_str
str_salt = hash_str + str(merchant_salt)
print str_salt
message = bytes(str_salt).encode('utf-8')
secret = bytes(merchant_key).encode('utf-8')
# paytr_token = base64.b64encode(hmac.new(str(merchant_key), str_salt, digestmod = hashlib.sha256).digest())
paytr_token = base64.b64encode(hmac.new(secret, message, digestmod = hashlib.sha256).digest())
print paytr_token
values = {
'merchant_id' : merchant_id,
'user_ip' : user_ip ,
'merchant_oid' : merchant_oid ,
'email' : str(email) ,
'payment_amount' : int(payment_amount) ,
'currency' : str(currency) ,
'user_basket' : user_basket,
'no_installment' : no_installment,
'max_installment' : max_installment,
'paytr_token' : paytr_token,
'user_name' : str(partner.name),
'user_address' : str(partner.street),
'user_phone' : str(partner.phone),
'merchant_ok_url' : str(merchant_ok_url),
'merchant_fail_url' : str(merchant_fail_url),
'test_mode' : test_mode,
'debug_on' : int(debug_on),
'timeout_limit' : int(timeout_limit),
'lang' : "en",
}
print values
post_data = urlencode(values)
print "postfields : " +post_data
buff = cStringIO.StringIO()
buff = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.paytr.com/odeme/api/get-token')
c.setopt(c.POSTFIELDS, post_data)
c.setopt(c.VERBOSE, True)
c.setopt(c.WRITEDATA, buff)
resp_data = c.perform()
print('Status: %d' % c.getinfo(c.RESPONSE_CODE))
print('Status: %f' % c.getinfo(c.TOTAL_TIME))
c.close()
data = buff.getvalue().decode('utf-8')
buff.close()
resp_data = json.load(resp_data)
if resp_data['status'] =='success':
token = resp_data['token']
else :
print resp_data['reason']
template = 'retailer_payment.pay_now'
return request.render(template, token)
With this, result contains nothing and throws:
AttributeError: 'NoneType' object has no attribute 'read'
Can someone help me to understand what's wrong here?
Trying to get the average from values returned in a for loop and print it next to group name. I can get it to calculate the average and print it under the return but not next to the first print as in Group 2...
When I add the argument as in Group 2, I get this error:
print "Group 2 - %s%%" % (avg)
NameError: name 'avg' is not defined
Not sure what I'm doing wrong, please help. If anyone has an easier way to do this please feel free to suggest.
The end result I'm looking for should be as follows:
Group 1 - 100%
name1 100
name2 100
name3 100
Group 2 - 100%
name1 100
name2 100
name3 100
Here is my script so far:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import pycurl
import time
from io import BytesIO
# Which monitors should data be retrieved for?
grp1 = ['000000000000000000', '000000000000000000', '000000000000000000']
grp2 = ['000000000000000000', '000000000000000000', '000000000000000000']
# Make calls to get the availability details
def connectMethod(method, url):
c = pycurl.Curl()
connectReturn = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ["Authorization: authtoken 00000000000000000000000000000000"])
c.setopt(c.WRITEFUNCTION, connectReturn.write)
c.setopt (pycurl.CUSTOMREQUEST, method)
c.perform()
c.close()
connectOutput = connectReturn.getvalue()
return connectOutput
returned_items = {}
avail = list()
print "Group 1"
for item in group1:
base_url = 'https://www.domain.com/api/reports/summary/'
putData = item + '?period=13&unit_of_time=1'
req_url = base_url + putData
listOfAvail = json.loads(connectMethod('GET', req_url))
returned_items[item] = listOfAvail
name = listOfAvail['data']['info']['resource_name']
avail_pct = listOfAvail['data']['summary_details']['availability_percentage']
avg_avail = avail.append(avail_pct)
print "%s\t%s%%" % (name, avail_pct)
avg = float(sum(avail))/len(avail)
print avg
print "Group 2 - %s%%" % (avg)
for item in group2:
base_url = 'https://www.domain.com/api/reports/summary/'
putData = item + '?period=13&unit_of_time=1'
req_url = base_url + putData
listOfAvail = json.loads(connectMethod('GET', req_url))
returned_items[item] = listOfAvail
name = listOfAvail['data']['info']['resource_name']
avail_pct = listOfAvail['data']['summary_details']['availability_percentage']
avg_avail = avail.append(avail_pct)
print "%s\t%s%%" % (name, avail_pct)
avg = float(sum(avail))/len(avail)
print avg
Quick, dirty, and ugly, but it should point you in the right direction to get it figured out and cleaned up a bit.
I just modified your code to output what you're asking for.
(I hard coded the names and percentages where you're invoking the web call)
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import pycurl
import time
from io import BytesIO
# Which monitors should data be retrieved for?
group1 = ['000000000000000000', '000000000000000000', '000000000000000000']
group2 = ['000000000000000000', '000000000000000000', '000000000000000000']
# Make calls to get the availability details
def connectMethod(method, url):
c = pycurl.Curl()
connectReturn = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ["Authorization: authtoken 00000000000000000000000000000000"])
c.setopt(c.WRITEFUNCTION, connectReturn.write)
c.setopt (pycurl.CUSTOMREQUEST, method)
c.perform()
c.close()
connectOutput = connectReturn.getvalue()
return connectOutput
def pprint(title, names, averages):
avg = float(sum(percentages))/len(percentages)
print "%s - %s%%" % (title, avg)
for i in range(len(names)):
print "%s\t%s" % (names[i], percentages[i])
returned_items = {}
percentages = []
names = []
for item in group1:
base_url = 'https://www.domain.com/api/reports/summary/'
putData = item + '?period=13&unit_of_time=1'
req_url = base_url + putData
#listOfAvail = json.loads(connectMethod('GET', req_url))
returned_items[item] = {"name": "item 1" } #listOfAvail
name = "blah" # listOfAvail['data']['info']['resource_name']
avail_pct = 60 # listOfAvail['data']['summary_details']['availability_percentage']
names.append(name)
percentages.append(avail_pct)
pprint("Group 1", names, percentages)
print("")
del percentages[:]
del names[:]
for item in group2:
base_url = 'https://www.domain.com/api/reports/summary/'
putData = item + '?period=13&unit_of_time=1'
req_url = base_url + putData
#listOfAvail = json.loads(connectMethod('GET', req_url))
returned_items[item] = {"name": "item 2" } #listOfAvail
name = "asdf" #listOfAvail['data']['info']['resource_name']
avail_pct = 87 #listOfAvail['data']['summary_details']['availability_percentage']
names.append(name)
percentages.append(avail_pct)
pprint("Group 1", names, percentages)
This outputs:
Group 1 - 60.0%
blah 60
blah 60
blah 60
Group 1 - 87.0%
asdf 87
asdf 87
asdf 87
Essentially you just need to perform all your calculations first, and then print the results.
Some thoughts to help you clean this up a bit
Code Reuse:
The code in the for loops is nearly identical. Refactor this into a function where you pass the group, url, etc. (does this make sense)?
Have a look into the requests library, it could condense your web call code quite a bit.
I got a CSV file with numbers and I want to insert these numbers into a specific location in an url : jus after " "value": "
Here is my code :
with open('update_cases_id.csv') as p:
for lines in p:
uuid = lines.rstrip()
url_POST = "www.example.com/"
values = {}
values['return_type'] = 'retrieval'
values['format'] = 'TSV'
values['size'] = '70'
values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value": .format(uuid)}}]}'
data = urllib.urlencode(values)
url_final = url_POST + '?' + data
req2 = urllib2.Request(url_final)
req2.add_header('cookie', cookie)
handle = urllib2.urlopen(req2)
( edited :
example input : 123456-123456-987654
example output : it s data text )
You can do this with string formatting, this should work for you:
# ...snip
values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":%s}]}' % uuid
# snip...
The %s will be replaced by the uuid by the % replacement operator:
>>> values = {}
>>> uuid = 1234
>>> values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":%s}]}' % uuid
>>> values
{'filters': '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":1234}]}'}
Try to use Template.
from string import Template
params = Template('{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value": ${your_value}}}]}')
params = params.safe_substitute(your_value=123)
# params is '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":123}]}'