Ive the following function which is do POST request to provider , I need to add new param to post request to incress the timeout ( which is by default is 5 mints i want to incress it to 1 hour , i did changes but i keep getting errors
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/opt/lvptest/lvp_upload.py", line 226, in run
op = uploadMedia(mediaName, "PyUploader", env)
File "/opt/lvptest/lvp_upload.py", line 121, in uploadMedia
expires = math.ceil(time() + 3000) ["expires"]
TypeError: 'module' object is not callable
Here is my function
def uploadMedia(filepath, description, env):
global verbose
global config
orgId = config[env]["org_id"]
accessKey = config[env]["access_key"]
secret = config[env]["secret"]
expires = math.ceil(time() + 3000) ["expires"]
filename = os.path.basename(filepath)
baseUrl = "http://api.videoplatform.limelight.com/rest/organizations/%s/media" %(orgId)
signedUrl = lvp_auth_util.authenticate_request("POST", baseUrl, accessKey, secret, expires)
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.HEADER, 0)
c.setopt(c.HTTPPOST, [('title', filename), ("description", description), (("media_file", (c.FORM_FILE, filepath)))])
if verbose:
c.setopt(c.VERBOSE, 1)
bodyOutput = StringIO()
headersOutput = StringIO()
c.setopt(c.WRITEFUNCTION, bodyOutput.write)
c.setopt(c.URL, signedUrl)
c.setopt(c.HEADERFUNCTION, headersOutput.write)
try:
c.perform()
c.close()
Any tips if im mistaken adding param "expires" ?
here is example how is my POST request looks like
POST /rest/organizations/9fafklsdf/media?access_key=sfdfsdfsdfsdfsdf89234 &expires=1400406364&signature=Mc9Qsd4sdgdfg0iEOFUaRC4iiAJBtP%2BMCot0sFKM8A$
Two errors:
You should do from time import time instead of just time. Because the time module has a time function inside it.
math.ceil returns a float and you are trying to use it as a dict after:
expires = math.ceil(time() + 3000) ["expires"]
This doesn't make sense. math.ceil(time() + 3000) will be equal to something like 1400406364 and you can't retrieve a data from it.
Removing the ["expires"] should solve the problem.
The time module is not callable, you need to call time method from it:
>>> import time
>>> import math
>>> math.ceil(time())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> math.ceil(time.time())
1400657920.0
Then you need to get rid of ["expires"] after it, since it will return a float number not a dictionary.
I don't know why you are using cURL here, with requests your code is a lot simpler:
import time
import math
import urllib
import requests
url = 'http://api.videoplatform.limelight.com/rest/organizations/{}/media'
filename = 'foo/bar/zoo.txt'
params = {}
params['access_key'] = 'dfdfdeef'
params['expires'] = math.ceil(time.time()+3000)
url = '{}?{}'.format(url.format(org_id), urllib.urlquote(params))
payload = {}
payload['title'] = os.path.basename(filename)
payload['description'] = 'description'
file_data = {'media_file': open(filename, 'rb')}
result = requests.post(url, data=payload, files=file_data)
result.raise_for_status() # This will raise an exception if
# there is a problem with the request
Related
I want to read to humidity data from the API but I keep getting an atribute error.
Anybody can help, I am new to coding and python.
Error:
Traceback (most recent call last):
File "C:\Users...HidenForPrivacy", line 27, in <module>
test.current_humidity()
File "C:\Users...HidenForPrivacy", line 20, in current_humidity
response = requests.get(self.url)
AttributeError: 'humidity' object has no attribute 'url'
import requests
import json
class humidity():
def init(self,humidity, url):
self.humidity = humidity
self.api_key = "hiddenforprivacy"
self.lat = "53.5502"
self.lon = "9.9920"
self.url = url
def current_humidity(self):
response = requests.get(self.url)
data = json.loads(response.text)
self.url = "https://api.openweathermap.org/data/2.5/onecall?lat=%s&lon=%s&appid=%s&units=metric" % (self.lat, self.lon, self.api_key)
self.humidity = data["current"]["humidity"]
print(humidity)
test = humidity()
test.current_humidity()
The problem is that you have not yet set any value to self.url
When you call test = humidity(), you do not call the init(self, humidity, url) method, but the empty __init__(self) method (the constructor in Python is called __init__). So there the url is not set.
In your code you do set the url in line 22 self.url = "https://api.openweath..., but that happens after you already called response = requests.get(self.url).
One solution might be to put the line self.url = "https://api.openweath... before response = requests.get(self.url)
(Ignoring that g.text and p.content return "You're not authorised to view this content" from plug.dj) I get the error
Traceback (most recent call last):
File "plugling.py", line 20, in <module>
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
TypeError: cannot concatenate 'str' and 'Response' objects
When running this code:
import time
from websocket import create_connection
import requests
import calendar
slug = 'sfoc'
r = create_connection("wss://godj.plug.dj/socket")
t = calendar.timegm(time.gmtime())
token = 'https://plug.dj/_/auth/token'
join = 'https://plug.dj/_/rooms/join'
pl = {'slug': 'sfoc'}
g = requests.get(token)
print g.text
p = requests.post(join, data=pl)
print p.content
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
result = r.recv()
print result
r.close()
It didn't like me using %s for the variables either. I don't know what I'm doing wrong. Thanks in advance and let me know if I haven't explained something clearly.
You are trying to concatenate a Response object:
g = requests.get(token)
# ...
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
g is the response object. You wanted to get the text value:
r.send('{"a": "auth", "p": "' + g.text + '", "t":' + t + '}')
You may want to look at the json module if you are trying to send JSON data there:
r.send(json.dumps({'a': 'auth', 'p': g.text, 't': t}))
Running the code below
import threading
import io
import Client
Proxies = None
Users = None
with open("proxies.txt") as x:
Proxies = x.readlines()
with open("ids.txt") as f:
Users = f.readlines()
c = 0
for udata in Users:
uid = udata.split(':')[0]
ok = udata.split(':')[1]
while True:
proxy = Proxies[c].strip('\n')
proxySplit = proxy.split(':')
c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281)
if(c):
c += 1
break
I've got this exception:
Traceback (most recent call last):
File "Run.py", line 20, in <module>
proxy = str(Proxies[c]).strip('\n')
TypeError: object cannot be interpreted as an index
I can not found what's wrong with my code. Any help will be appreciated.
It seems that in line 22 c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281) you make c an object, not an int anymore. And when it goes to line 20 again, c is used as an index, which is not allowed.
I am trying to send a screenshot over a network via Python Wx. I am able to take a screenshot and save it to the filesystem, but I do not want to save it. I want to get the Base 64 code and send it without saving.
Here is my current attempt:
#!/usr/bin/env python
import requests
import socket
import time
import wx
import base64
def checkServer():
sesh = requests.session()
app = wx.App(False)
while True:
s = wx.ScreenDC()
w, h = s.Size.Get()
b = wx.EmptyBitmap(w, h)
m = wx.MemoryDCFromDC(s)
m.SelectObject(b)
m.Blit(0, 0, w, h, s, 0, 0)
m.SelectObject(wx.NullBitmap)
#outputs: <wx._gdi.Bitmap; proxy of <Swig Object of type 'wxBitmap *' at 0x2001640> >
#print b
#Does NOT Work, outputs: TypeError: must be convertible to a buffer, not Bitmap
#base64img = base64.b64encode(b)
# Works, but not what I want to do
#b.SaveFile("screenshot.png", wx.BITMAP_TYPE_PNG)
hostname = socket.gethostname()
url = 'http://localhost/callcenter/monitor/post.php'
payload = {
'host' : hostname,
#'image' : base64img
}
headers = {
'Connection' : "keep-alive",
'Content-Type' : "application/x-www-form-urlencoded"
}
r = sesh.post(url, data=payload, headers=headers, allow_redirects=False, verify=False)
content = r.text
print content
time.sleep(5)
checkServer()
How can I get the Base 64 code in a string from the bitmap b?
EDIT
I also tried:
buf=io.BytesIO()
b.CopyToBuffer(buf)
base64img = base64.b64encode(buf)
print base64img
and got this:
File "./main.py", line 51, in <module>
checkServer()
File "./main.py", line 29, in checkServer
b.CopyToBuffer(buf)
File "/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode/wx/_gdi.py", line 740, in CopyToBuffer
return _gdi_.Bitmap_CopyToBuffer(*args, **kwargs)
TypeError: expected a readable buffer object
Edit 2
Tried this:
buf=bytearray()
b.CopyToBuffer(buf)
base64img = base64.b64encode(buf)
print base64img
And got something different this time:
Traceback (most recent call last):
File "./main.py", line 51, in <module>
checkServer()
File "./main.py", line 29, in checkServer
b.CopyToBuffer(buf)
File "/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode/wx/_gdi.py", line 740, in CopyToBuffer
return _gdi_.Bitmap_CopyToBuffer(*args, **kwargs)
ValueError: Invalid data buffer size.
You could try this:
base64img = base64.b64encode(b.ConvertToImage().GetData())
Below is the code I have been working on.
The very last line write_csv('twitter_gmail.csv', messages, append=True) throws a
[ec2-user#ip-172-31-46-164 ~]$ ./twitter_test16.sh
Traceback (most recent call last):
File "./twitter_test16.sh", line 53, in
write_csv('twitter_gmail.csv', messages, append=True)
NameError: name 'messages' is not defined
I have messages defined so I dont understand why it would do that.
import csv
import json
import oauth2 as oauth
import urllib
import sys
import requests
import time
CONSUMER_KEY = "
CONSUMER_SECRET = "
ACCESS_KEY = "
ACCESS_SECRET = "
class TwitterSearch:
def __init__(self, ckey=CONSUMER_KEY, csecret=CONSUMER_SECRET,
akey=ACCESS_KEY, asecret=ACCESS_SECRET,
query='https://api.twitter.com/1.1/search/tweets.{mode}?{query}'
):
consumer = oauth.Consumer(key=ckey, secret=csecret)
access_token = oauth.Token(key=akey, secret=asecret)
self.client = oauth.Client(consumer, access_token)
self.query = query
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
return self.client.request(self.query.format(query=query, mode=mode))
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = TwitterSearch()
response, data = ts.search('#gmail.com', result_type='recent')
js = json.loads(data)
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] \
for msg in js.get('statuses', []))
write_csv('twitter_gmail.csv', messages, append=True)
The previous line is missing a parenthesis.
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', [])
Should be:
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
I'm surprised that it works when you change to print? Are you also changing the comprehension when you do that?
You asked why the line number of the error was after the bad syntax?
Try putting this in line one of a file and running it, and note the line of the SyntaxError.
a = (]
Then try this and check out the line number:
a = (
b = "some stuff"
Finally, try this:
a = (
b = "some stuff"
Think about when you would know that the programmer had made a python-illegal typo if you were reading the code and carrying it out via pen and paper.
Basically, a SyntaxError is raised as soon as it can be unambiguously determined that invalid syntax was used, which is often immediately after a statement where a mistake was made, not immediately at.
You'll frequently get line numbers on SyntaxErrors that are a line (or several lines if there's empty lines or a corner case) below the actual typo.