I get a response object from Tweepy's client.get_tweet:
Response(data=<Tweet id=000 text='tweet string'>, includes={'users': [<User id=000 name=J username=j>]}, errors=[], meta={})
Traceback (most recent call last):
File "tweet.py", line 41, in <module>
print(tweets.json())
AttributeError: 'Response' object has no attribute 'json'
but whatever I do to try and print the raw content of the Response, I can't get it done (as above). Ideally, I would just print it all as one big JSON.
I tried looping over response and printing each element, json()ing it all as I saw here:
https://developer.mozilla.org/en-US/docs/Web/API/Response/json
but nothing quite works. It either returns partial information, no information, or an error.
Related
I am attempting to make a PUT fetch request from my jQuery file. The server giving me a 500, as the fetch is not able to be used by my controller.
This is the stream that is being sent to my .rb file in the form of request.body:
request.body == #<StringIO:0x00005597c3b69fa8>
request.body.string == "{\"name\":\"New School\",\"office_id\":2,\"inactive\":false}"
I have tried..
load(request.body.string)
But this returns a load error:
LoadError: cannot load such file -- {"name":"New School","office_id":2,"inactive":false}
Also..
parse(request.body.string)
which results in
undefined method `parse' for #<CrEventsApp:0x00005597c3bbf098>
Is there a method that will parse this information back into a hash? I can parse through the string myself with some regex and .split() to get the data into a useable format, but I would like a more concise and robust solution.
JSON.parse should do the trick:
JSON.parse(request.body.string)
=> {"name"=>"New School", "office_id"=>2, "inactive"=>false}
I'm adding new applications to an existing Django project, and encountered something I am unable to debug. The callback error is "AttributeError: 'QuerySet' object has no attribute 'META'", but I'm not sure that's what's going on. I've written 4 of these apps for different API objects today, and had no issues. When I add print() debug messages to the functions, what I find is that the execution seems to be jumping out of my lead_lists view function and into my lists view function before it errors.
This is my list.views.py
def list(request):
print("we're in lists view")
lists = List.objects.all()
print("lists saved for context")
context = {'lists': lists}
print("context created")
return render(request, 'list.html', context) # fails here
def load_lists(request):
api_lists = services.get_lists()
print("api lists loaded")
db_list_ids = list(List.objects.values_list('list_id', flat=True)) # jumps out of function here
print("db lists loaded") # this never prints
print(f"db_list_ids: {db_list_ids}")
for api_list in api_lists:
if api_list['id'] not in db_list_ids:
api_list = services.transform_list(api_list)
form = ListModelForm(api_list)
if form.is_valid():
form.save
else:
return HttpResponse(form.errors)
print("exited load loop")
lists = List.objects.all()
print("load lists objects saved")
context = {'lists': lists}
print("load lists context saved")
return render(request, 'load_lists.html', context)
The expected result is, when I navigate to /list/load it runs the load_lists view function. Here is the output I get from the console.
we're in lists view
lists saved for context
context created
[31/Jul/2019 16:20:32] "GET /list/ HTTP/1.1" 200 2458
api lists loaded
we're in lists view
lists saved for context
context created
Internal Server Error: /list/load/
Traceback (most recent call last):
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\David.Wilcox\ongage-django\ongage\list\views.py", line 19, in load_lists
db_list_ids = list(List.objects.values_list('list_id', flat=True))
File "C:\Users\David.Wilcox\ongage-django\ongage\list\views.py", line 14, in list
return render(request, 'list.html', context)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\template\base.py", line 169, in render
with context.bind_template(self):
File "c:\users\david.wilcox\appdata\local\programs\python\python37-32\Lib\contextlib.py", line 112, in __enter__
return next(self.gen)
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\template\context.py", line 246, in bind_template
updates.update(processor(self.request))
File "C:\Users\David.Wilcox\ongage-django\venv\lib\site-packages\django\template\context_processors.py", line 40, in debug
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
AttributeError: 'QuerySet' object has no attribute 'META'
[31/Jul/2019 16:20:36] "GET /list/load/ HTTP/1.1" 500 103930
I originally thought it wasn't playing nicely due to the usage of the word 'list', so I refactored and renamed my variables, but the error is the same.
Short answer: please do not name your views after Python builtins like list. You can rename the view function to view_lists.
You here defined a function named list. As a result, if you later use list(List.objects.values_list('list_id', flat=True)) in your load_lists view, you will indeed call the view function, and not the builtin function, since that identifier now points to your view function.
You can for example rename it to view_lists, like:
# rename view function
def view_lists(request):
return render(request, 'list.html', {'lists': List.objects.all()})
def load_lists(request):
api_lists = services.get_lists()
db_list_ids = list(List.objects.values_list('list_id', flat=True))
print(f"db_list_ids: {db_list_ids}")
for api_list in api_lists:
if api_list['id'] not in db_list_ids:
api_list = services.transform_list(api_list)
form = ListModelForm(api_list)
if form.is_valid():
form.save()
else:
return HttpResponse(form.errors)
lists = List.objects.all()
return render(request, 'load_lists.html', context = {'lists': lists})
Note that you need to call the save() function on your form, so form.save(), not form.save.
PEP-8 recommends adding a trailing underscore if there is no better name than a builtin one:
If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
(...)
If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)
I was successfully pulling tweets from the Twitter API until I decided to put the keys/tokens in a separate configuration file. As I plan on uploading the main file to Github.
The solutions on StackOverflow that I found so far didn't solve my problem, unfortunately.
import oauth2 as oauth
import json
import configparser
config = configparser.RawConfigParser()
configpath = r'config.py'
config.read(configpath)
consumer_key = config.get('logintwitter', 'consumer_key')
consumer_secret = config.get('logintwitter', 'consumer_secret')
access_key = config.get('logintwitter', 'access_key')
access_secret = config.get('logintwitter', 'access_secret')
consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) #twitter: sign me in
access_token = oauth.Token(key=access_key, secret=access_secret) #grant me access
client = oauth.Client(consumer, access_token) #object return
timeline_endpoint = "https://api.twitter.com/1.1/statuses/home_timeline.json"
response, data = client.request(timeline_endpoint)
tweets = json.loads(data) #take a JSON string convert it to dictionary structure:
for tweet in tweets:
print(tweet["text"])
This is the error message:
Traceback (most recent call last):
File
"/Users/myname/PycharmProjects/twiiter2/twitterconnect.py", line 24,
in
print(tweet["text"]) TypeError: string indices must be integers
I tried changing the json.loads() method as well as the content in print(tweet["text"])
Humbled for anyon to point me in the right direction.
Thank you!
Input:
CONSUMER_KEY = '3zu*************BClmA'
CONSUMER_SECRET = 'pQ************vgJmrysYYWGwSSwA0HzFvB'
OAUTH_TOKEN = '2431620*****************Z9kOlXGWgj9U9hJNSZlAAP'
OAUTH_TOKEN_SECRET = 'a**************9j7aJsXqLmOcsbm'
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
#print twitter_api
WORLD_WOE_ID = 1
US_WOE_ID = 23424977
world_trends = twitter_api.trends.place(_id=WORLD_WOE_ID)
us_trends = twitter_api.trends.place(_id=US_WOE_ID)
print world_trends
print
print us_trends
Output:
<twitter.api.Twitter object at 0x7fae2a3fa750>
Traceback (most recent call last):
File "tw1.py", line 22, in <module>
world_trends = twitter_api.trends.place(_id=WORLD_WOE_ID)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 239, in __call__
return self._handle_response(req, uri, arg_data, _timeout)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 270,in handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/trend/place.json using parameters: (id=1&oauth_consumer_key=3zuNBJp5pSNsL2TQdBClmA&oauth_nonce=2012443237312860371&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1396954063&oauth_token=2431620524-S7HkBF47N49xLiqKlZ9kOlXGWgj9U9hJNSZlAAP&oauth_version=1.0&oauth_signature=7%2FSvFNAnLw9xToRMxr97d9eaPL4%3D)
details: {"errors":[{"message":"Could not authenticate you","code":32}]}
Does anybody know why is this error happening?
The error 401 means that the request was unauthorized per the Twitter Error Codes & Responses page. There are two types of authentication--application-specific and OAuth. You're using OAuth:
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
This means that either your request was bad or your authentication credentials were. Looking again at the Error Codes & Responses page linked above, an error code of 32 like you see here:
details: {"errors":[{"message":"Could not authenticate you","code":32}]}
Means that there's probably something wrong with your authentication credentials. First, check to make sure that your application has the proper permissions (i.e. read/write) based on what you're trying to do. You appear to just be getting trends so that should be fine. Try regenerating your API keys/access tokens on your application page on your Twitter app page and you should be all set!
I try to use Sikuli. I will have 2 Files. One of them will be the "main" file and one of then is for functions.
The main-file I have called "test" and the file for the Function I have called "importi".
If I run the main file, I will get the error:
[error] Fehlermeldung: Traceback (most recent call last): File
"C:...\Temp\sikuli-tmp8331266965127754273.py",line 3, in
importi.help()
AttributeError: 'module'object has no attribute 'hallo'
This is my Code of the main-file:
import importi
importi.hallo()
and this is the code of the File with the function:
anzeige = "Hallo"
def help():
popup(anzeige)
I think in the calling function you should write -
import importi
importi.help()
in above code "help" is the function name defined in called (or imported) function.
At the same time, below code should be saved as importi.sikuli file.
anzeige ="Hallo"
def help():
popup(anzeige)
So, to summarize.
File importi.sikuli has -
anzeige ="Hallo"
def help():
popup(anzeige)
And calling function (whatever name it has) is -
import importi
importi.help()