Why am I getting KeyError in the following python code? - python

I wanna execute this code.
This is the error I'm getting in terminal after running the code
Traceback (most recent call last):
File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 68, in <module>
print 'total='+str(process_posts(url))
File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 32, in process_posts
posts=res_obj["data"]
KeyError: 'data'
The code is -
import httplib, urllib
from bs4 import BeautifulSoup
import os
import json
import time
import calendar
access_token='value'
dob='2015-07-30'
conn = httplib.HTTPSConnection("graph.facebook.com")
print 'requesting...'
#conn.request("GET",path,urllib.urlencode(data),{})
has_more=False
def convert_to_local(s):
t=time.strptime(s[:19],"%Y-%m-%dT%H:%M:%S")
t=time.localtime(calendar.timegm(t))
t=time.strftime("%Y-%m-%d",t)
return t
def getRandomThnx(msg):
return 'thanks :)'
def process_posts(url):
conn = httplib.HTTPSConnection("graph.facebook.com")
conn.request("GET",url)
res = conn.getresponse()
conn.getresponse
data=res.read()
res_obj=json.loads(data)
posts=res_obj["data"]
processed=0
for post in posts:
if not "message" in post:
continue
msg=post["message"]
post_date=convert_to_local(post["created_time"])
if dob == post_date:
if "from" in post and "message" in post:
user= post["from"]["name"]
path='/'+post['id']+'/comments'
param_data={ 'format':'json',
'message':getRandomThnx(msg),
'access_token':access_token
}
conn = httplib.HTTPSConnection("graph.facebook.com")
if post["comments"]["count"]==0:
print 'responding to :'+user+'->'+msg
conn.request("POST",path,urllib.urlencode(param_data),{})
res = conn.getresponse()
path='/'+post['id']+'/likes'
param_data={ 'format':'json',
'access_token':access_token
}
conn = httplib.HTTPSConnection("graph.facebook.com")
processed+=1
if "paging" in res_obj:
return processed+process_posts(res_obj["paging"]["next"] [len("https://graph.facebook.com"):])
else:
print "Finished"
return processed
url='/me/feed?access_token='+access_token
print 'total='+str(process_posts(url))
print 'Thanx to all wisher :)'

It means that the data json you receive in response to your GET query doesn't contain a "data" key.
You can visualise how the json data looks like by doing something like:
import httplib, urllib
from bs4 import BeautifulSoup
import os
import json
import time
import calendar
access_token='value'
dob='2015-07-30'
conn = httplib.HTTPSConnection("graph.facebook.com")
print 'requesting...'
#conn.request("GET",path,urllib.urlencode(data),{})
has_more=False
def convert_to_local(s):
t=time.strptime(s[:19],"%Y-%m-%dT%H:%M:%S")
t=time.localtime(calendar.timegm(t))
t=time.strftime("%Y-%m-%d",t)
return t
def getRandomThnx(msg):
return 'thanks :)'
def process_posts(url):
conn = httplib.HTTPSConnection("graph.facebook.com")
conn.request("GET",url)
res = conn.getresponse()
conn.getresponse
data=res.read()
res_obj=json.loads(data)
try:
posts=res_obj["data"]
except:
print "res_obj does not contain 'data', here is what res_obj looks like:"
print data
...

Related

Tweepy Paginator AttributeError: 'Response' object has no attribute 'meta'

I am trying to print tweet data but I get an error that I can't fix. When I try and run the code in the docs I still get the same error. Is this a python 3.8 issue?
Code in docs:
for tweet in tweepy.Paginator(client.search_recent_tweets, "Tweepy",
max_results=100).flatten(limit=250):
print(tweet.id)
Stack Trace:
Traceback (most recent call last):
File "scraper.py", line 38, in <module>
main()
File "scraper.py", line 34, in main
for item in paginator:
File "/Users/troy/Desktop/streamlit/env/lib/python3.8/site-packages/tweepy/pagination.py", line 100, in __next__
self.previous_token = response.meta.get("previous_token")
AttributeError: 'Response' object has no attribute 'meta'
My Code:
import tweepy
import requests
import os
import pandas as pd
# global tokens
api_key = os.environ.get('Twitter_API_Key')
api_secret = os.environ.get('Twitter_API_Secret')
access_token = os.environ.get('Twitter_Access_Token')
access_secret = os.environ.get('Twitter_Access_Secret')
bearer = os.environ.get('bearer_token')
def create_client():
client = tweepy.Client( bearer_token=bearer,
return_type=requests.Response,
wait_on_rate_limit=True)
return client
def create_paginator(authenticated_client):
paginator = tweepy.Paginator(
authenticated_client.search_recent_tweets,
query='from:elonmusk',
tweet_fields=['author_id', 'id', 'created_at'],
max_results=100,
limit=5)
return paginator
def main():
client = create_client()
paginator = create_paginator(client)
print(paginator)
for item in paginator:
print(item)
if __name__ == "__main__":
main()
Turns out I needed .flatten(). Don't know why but hey that's show business.
def create_paginator(authenticated_client, query):
paginator = tweepy.Paginator(authenticated_client.search_recent_tweets, query=query,
tweet_fields=['author_id', 'id', 'created_at'],max_results=10).flatten(limit=5)

Python MagicMock returns bytes value for HTTP response

I want to mock HTTP request that returns an image (bytes) with MagicMock. So, I have simple function here:
import io
import urllib.request
def blah():
try:
req = urllib.request.Request(url='<image url/base64>', data=None, method='GET')
response = urllib.request.urlopen(req)
except Exception as e:
return str(e)
body = io.BytesIO(response.read()) # error here
return 'something'
And I want test it, like this:
import unittest
from blah import blah
from unittest.mock import patch, MagicMock
class TestBlah(unittest.TestCase):
def test_blah(self):
with patch('urllib.request.urlopen') as mock_urlopen:
cm = MagicMock()
cm.getcode.return_value = 200
cm.read.return_value = open('./download.jpeg') # an image file
cm.__enter__.return_value = cm
mock_urlopen.return_value = cm
self.assertEqual(blah(), 'something')
When I execute my code, it produces error:
TypeError: a bytes-like object is required, not '_io.TextIOWrapper'
Can anyone help me?
It should be like this,
cm.read.return_value = open('./download.jpeg', 'rb').read()

TypeError: check_database() takes 2 positional arguments but 3 were given

Writing bot to crawl a forum and send a report via email to a user based on keywords. Having some trouble.
Also a little concerned that my imports are incorrect, as I am attempting to muddle way through this.
Getting this error set when I run it (Obviously email info was ****):
E:\>python dgcrbot.py
Traceback (most recent call last):
File "dgcrbot.py", line 95, in <module>
main()
File "dgcrbot.py", line 91, in main
Email('*****')
File "dgcrbot.py", line 67, in __init__
self.run()
File "dgcrbot.py", line 87, in run
self.send_message()
File "dgcrbot.py", line 70, in send_message
matches = Site('http://www.dgcoursereview.com/forums/forumdisplay.php?f=2')
File "dgcrbot.py", line 23, in __init__
self.check_posts()
File "dgcrbot.py", line 55, in check_posts
if any(pattern.lower() in title.lower() for pattern in patterns) and self.check_database(self, posts[title]) is False:
TypeError: check_database() takes 2 positional arguments but 3 were given
Full Dump
import re
import sqlite3
import urllib.request
import html.parser
import smtplib
from bs4 import BeautifulSoup
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
patterns = [****]
data = sqlite3.connect('discgolf.db')
cur = data.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS checked(id)')
data.commit()
server = smtplib.SMTP()
class Site(object):
def __init__(self,forum):
self.forum = forum
self.check_posts()
def get_url(self):
posts = {}
html = BeautifulSoup(urllib.request.urlopen(self.forum).read().decode('utf-8','ignore'),'html.parser')
titles = html.find_all('td',class_='alt1')
for title in titles:
try:
url = str(title)[re.search('<a href="',str(title)).span()[1]:]
url = url[:re.search('">',url).span()[0]]
url = url[re.search('amp;t=',url).span()[1]:]
title = str(title)[re.search('title=',str(title)).span()[1]:re.search('">',str(title)).span()[0]]
posts[title] = url
except:
pass
return posts
def check_database(self, identity):
cur.execute('SELECT * FROM checked WHERE id=?',[identity])
if cur.fetchone():
return True
else:
return False
def submit_to_database(self, identity):
cur.execute('INSERT INTO checked VALUES(?)',[identity])
data.commit()
def check_posts(self):
posts = self.get_url()
matches = {}
for title in posts:
if any(pattern.lower() in title.lower() for pattern in patterns) and self.check_database(self, posts[title]) is False:
permalink = 'http://www.dgcoursereview.com/forums/showthread.php?t={}'.format(post[title])
matches[title] = permalink
self.submit_to_database(posts[title])
return matches
class Email(object):
def __init__(self, to_address, from_address='*****'):
self.to_address = to_address
self.from_address = from_address
self.run()
def send_message(self,subject='Found Match', body='N/A'):
matches = Site('http://www.dgcoursereview.com/forums/forumdisplay.php?f=2')
msg = MIMEMultipart()
msg['From'] = self.from_address
msg['To'] = self.to_address
msg['Subject'] = DGCR - AutoBot
body = ''
for title in matches:
body += '{} -- {}\n\n'.format(title,matches[title])
msg.attach(MIMEText(body,'plain'))
server = smtplib.SMTP('*****')
server.starttls()
server.login(self.from_address,'*****')
text = msg.as_string()
server.send_email(self.from_address, self.to_address, text)
server.quit()
def run(self):
self.send_message()
def main():
while True:
Email('*****')
time.sleep(10*60)
if __name__ == '__main__':
main()

How do I read this stringified javascript variable into Python?

I'm trying to read _pageData from https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1 into Python 2.7.11 so that I can process it, using this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Testing _pageData processing. """
import urllib2
import re
import ast
import json
import yaml
BASE_URL = 'https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1'
def main():
""" Do the business. """
response = urllib2.urlopen(BASE_URL, None)
results = re.findall('var _pageData = \\"(.*?)\\";</script>', response.read())
first_result = results[0]
# These all fail
data = ast.literal_eval(first_result)
# data = yaml.load(first_result)
# data = json.loads(first_result)
if __name__ == '__main__':
main()
but get the following error:
Traceback (most recent call last):
File "./temp.py", line 24, in <module>
main()
File "./temp.py", line 19, in main
data = ast.literal_eval(first_result)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
[[1,true,true,true,true,true,true,true,true,,\"at\",\"\",\"\",1450364255674,\"\",\"en_US\",false,[]\n,\"https://www.google.com/maps/d/viewer?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/embed?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/edit?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/thumbnail?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",,,true,\"https://www.google.com/maps/d/print?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/pdf?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/viewer?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",false,false,\"/maps/d\",\"maps/sharing\",\"//www.google.com/intl/en_US/help/terms_maps.html\",true,\"https://docs.google.com/picker\",[]\n,false,true,[[[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-regular-001.png\",143,25]\n,[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-regular-2x-001.png\",286,50]\n]\n,[[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-small-001.png\",113,20]\n,[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-small-2x-001.png\",226,40]\n]\n]\n,1,\"https://www.gstatic.com/mapspro/_/js/k\\u003dmapspro.gmeviewer.en_US.8b9lQX3ifcs.O/m\\u003dgmeviewer_base/rt\\u003dj/d\\u003d0/rs\\u003dABjfnFWonctWGGtD63MaO3UZxCxF6UPKJQ\",true,true,false,true,\"US\",false,true,true,5,false]\n,[\"mf.map\",\"zBghbRiSwHlg.k2ATNtn6BCk0\",\"Hollywood, FL\",\"\",[-80.16005,26.01043,-80.16005,26.01043]\n,[-80.16005,26.01043,-80.16005,26.01043]\n,[[,\"zBghbRiSwHlg.kq4rrF9BNRIg\",\"Untitled layer\",\"\",[[[\"https://mt.googleapis.com/vt/icon/name\\u003dicons/onion/22-blue-dot.png\\u0026scale\\u003d1.0\"]\n,[]\n,1,1,[[,[26.01043,-80.16005]\n]\n,\"MDZBMzJCQjRBOTAwMDAwMQ~CjISKmdlby1tYXBzcHJvLm1hcHNob3AtbGF5ZXItNDUyOWUwMTc0YzhkNmI2ZBgAKAAwABIZACBawIJBU4Fe8v7vNSoAg0dtnhhVotEBLg\",\"vdb:\",\"zBghbRiSwHlg.kq4rrF9BNRIg\",[26.01043,-80.16005]\n,[0,-32]\n,\"06A32BB4A9000001\"]\n,[[\"Hollywood, FL\"]\n]\n,[]\n]\n]\n,,1.0,true,true,,,,[[\"zBghbRiSwHlg.kq4rrF9BNRIg\",1,,,,\"https://mapsengine.google.com/map/kml?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\\u0026lid\\u003dzBghbRiSwHlg.kq4rrF9BNRIg\",,,,,0,2,true,[[[\"06A32BB4A9000001\",[[[26.01043,-80.16005]\n]\n]\n,[]\n,[]\n,0,[[\"name\",[\"Hollywood, FL\"]\n,1]\n,,[]\n,[]\n]\n,,0]\n]\n,[[[\"https://mt.googleapis.com/vt/icon/name\\u003dicons/onion/22-blue-dot.png\\u0026filter\\u003dff\\u0026scale\\u003d1.0\",[16,32]\n,1.0]\n,[[\"0000FF\",0.45098039215686275]\n,5000]\n,[[\"0000FF\",0.45098039215686275]\n,[\"000000\",0.25098039215686274]\n,3000]\n]\n]\n]\n]\n]\n,[]\n,,,,,1]\n]\n,[2]\n,,,\"mapspro\",\"zBghbRiSwHlg.k2ATNtn6BCk0\",,true,false,false,\"\",2,false,\"https://mapsengine.google.com/map/kml?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",3807]\n]\n
^
SyntaxError: invalid syntax
var _pageData is in this format:
"[[1,true,true,true,true,true,true,true,true,,\"at\",\"\",\"\",1450364255674,\"\",\"en_US\",false,[]\n,\"https://www.google.com/maps/d/viewer?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/embed?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/edit?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/thumbnail?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",,,true,\"https://www.google.com/maps/d/print?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/pdf?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",\"https://www.google.com/maps/d/viewer?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",false,false,\"/maps/d\",\"maps/sharing\",\"//www.google.com/intl/en_US/help/terms_maps.html\",true,\"https://docs.google.com/picker\",[]\n,false,true,[[[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-regular-001.png\",143,25]\n,[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-regular-2x-001.png\",286,50]\n]\n,[[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-small-001.png\",113,20]\n,[\"//www.gstatic.com/mapspro/images/google-my-maps-logo-small-2x-001.png\",226,40]\n]\n]\n,1,\"https://www.gstatic.com/mapspro/_/js/k\\u003dmapspro.gmeviewer.en_US.8b9lQX3ifcs.O/m\\u003dgmeviewer_base/rt\\u003dj/d\\u003d0/rs\\u003dABjfnFWonctWGGtD63MaO3UZxCxF6UPKJQ\",true,true,false,true,\"US\",false,true,true,5,false]\n,[\"mf.map\",\"zBghbRiSwHlg.k2ATNtn6BCk0\",\"Hollywood, FL\",\"\",[-80.16005,26.01043,-80.16005,26.01043]\n,[-80.16005,26.01043,-80.16005,26.01043]\n,[[,\"zBghbRiSwHlg.kq4rrF9BNRIg\",\"Untitled layer\",\"\",[[[\"https://mt.googleapis.com/vt/icon/name\\u003dicons/onion/22-blue-dot.png\\u0026scale\\u003d1.0\"]\n,[]\n,1,1,[[,[26.01043,-80.16005]\n]\n,\"MDZBMzJCQjRBOTAwMDAwMQ~CjISKmdlby1tYXBzcHJvLm1hcHNob3AtbGF5ZXItNDUyOWUwMTc0YzhkNmI2ZBgAKAAwABIZACBawIJBU4Fe8v7vNSoAg0dtnhhVotEBLg\",\"vdb:\",\"zBghbRiSwHlg.kq4rrF9BNRIg\",[26.01043,-80.16005]\n,[0,-32]\n,\"06A32BB4A9000001\"]\n,[[\"Hollywood, FL\"]\n]\n,[]\n]\n]\n,,1.0,true,true,,,,[[\"zBghbRiSwHlg.kq4rrF9BNRIg\",1,,,,\"https://mapsengine.google.com/map/kml?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\\u0026lid\\u003dzBghbRiSwHlg.kq4rrF9BNRIg\",,,,,0,2,true,[[[\"06A32BB4A9000001\",[[[26.01043,-80.16005]\n]\n]\n,[]\n,[]\n,0,[[\"name\",[\"Hollywood, FL\"]\n,1]\n,,[]\n,[]\n]\n,,0]\n]\n,[[[\"https://mt.googleapis.com/vt/icon/name\\u003dicons/onion/22-blue-dot.png\\u0026filter\\u003dff\\u0026scale\\u003d1.0\",[16,32]\n,1.0]\n,[[\"0000FF\",0.45098039215686275]\n,5000]\n,[[\"0000FF\",0.45098039215686275]\n,[\"000000\",0.25098039215686274]\n,3000]\n]\n]\n]\n]\n]\n,[]\n,,,,,1]\n]\n,[2]\n,,,\"mapspro\",\"zBghbRiSwHlg.k2ATNtn6BCk0\",,true,false,false,\"\",2,false,\"https://mapsengine.google.com/map/kml?mid\\u003dzBghbRiSwHlg.k2ATNtn6BCk0\",3807]\n]\n"
I've tried replacing the \" and \n and decoding the \uXXXX before using, without success. I've also tried replacing ,, with ,"", and ,'', without success.
Thank you.
It seems like there are three kinds of syntactic errors in your string:
, followed by ,
[ followed by ,
, followed by ]
Assuming that those are supposed to be null elements (or ''?), you can just replace those in the original string -- exactly like you did for the ,, case, but you missed the others. Also, you have to do the ,, replacement twice, otherwise you will miss cases such as ,,,,. Then, you can load the JSON string with json.loads.
>>> s = "your messed up json string"
>>> s = re.sub(r",\s*,", ", null,", s)
>>> s = re.sub(r",\s*,", ", null,", s)
>>> s = re.sub(r"\[\s*,", "[ null,", s)
>>> s = re.sub(r",\s*\]", ", null]", s)
>>> json.loads(s)
I started off using ast.literal.eval(...) because I was under the (mistaken?) impression that javascript arrays and Python lists were mutually compatible, so all I had to do was destringify _pageData.
However, I hadn't noticed that Python doesn't like ,, true, false or [,. Fixing them does the trick (thank you #Two-Bit Alchemist and #tobias_k)
So, the following appears to work:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Testing _pageData processing. """
import urllib2
import re
import ast
import json
import yaml
BASE_URL = 'https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1'
def main():
""" Do the business. """
response = urllib2.urlopen(BASE_URL, None)
results = re.findall('var _pageData = \\"(.*?)\\";</script>', response.read())
first_result = results[0]
first_result = first_result.replace(',,,,,,', ',None,None,None,None,None,')
first_result = first_result.replace(',,,,,', ',None,None,None,None,')
first_result = first_result.replace(',,,,', ',None,None,None,')
first_result = first_result.replace(',,,', ',None,None,')
first_result = first_result.replace(',,', ',None,')
first_result = first_result.replace('[,', '[None,')
first_result = first_result.replace('\\"', '\'')
first_result = first_result.replace('\\n', '')
first_result = first_result.replace('true', 'True')
first_result = first_result.replace('false', 'False')
data = ast.literal_eval(first_result)
for entry in data:
print entry
if __name__ == '__main__':
main()

python error : 'module' object is not callable "math.ceil"

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

Categories

Resources