How to display specific cookie? - python

I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages.
I'd like to display a given cookie from the cookiejar instead of the whole thing:
#OK to display all the cookies
for index, cookie in enumerate(cj):
print index, ' : ', cookie
#How to display just PHPSESSID?
#AttributeError: CookieJar instance has no attribute '__getitem__'
print "PHPSESSID: %s" % cj['PHPSESSID']
I'm sure it's very simple but googling for this didn't return samples.
Thank you.

The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself.
I am not sure what cookie attribute you want do do the lookup on. Example, using name:
def get_cookie_by_name(cj, name):
return [cookie for cookie in cj if cookie.name == name][0]
cookie = get_cookie_by_name(cj, "PHPSESSID")
If you're not familiar with the [...] syntax, it is a list comprehension. The [0] then picks the first element of the list of matching cookies.

Related

How do I get individual userId, id, title and posts from jsonplaceholder.typecode.com

I need help with an assignment regarding API calls. Here are the following parameters:
use python to get on Api (https://jsonplaceholder.typicode.com)
import requests, json
url = 'https://jsonplaceholder.typicode.com/posts'
r = requests.get(url)
data = json.loads(r.text)
capture list of dictionaries from one endpoint and reverse sort
for item in reversed(data):
print(item)
Print a post for specific userId
print(data[0])
Print a post from specific userId that only prints out the title, id, or post
When I try:
print(data[0].id[1])
I get a 'dict' object has no attribute 'id'. Any help is appreciated. I just need help with question 4.
To access dictionary element in python you use dictionary['<key>'] (not dictionary.<key>). Try:
print(data[0]['id'])
print(data[0]['userId'])

Search google contact using People Api v3?

I'm trying to use google People API to search a person by her/his name field. Here is the code sample:
service = build('people', 'v1', credentials=creds)
request = service.people().searchContacts(pageSize=10, query="A", readMask="names")
print(request.body) # results in None, but there is a lot of contacts in my list starting from "A".
I used the following links:
https://developers.google.com/people/v1/contacts#python
https://googleapis.github.io/google-api-python-client/docs/dyn/people_v1.people.html#get
https://developers.google.com/people/quickstart/python
and the SCOPE is https://www.googleapis.com/auth/contacts.readonly.
I need a way to return a list of contacts using name mask (for ex, person with the name "Foo bar" should be found using "f", "F", "foo", and so on).
Answer:
You aren't executing your request, only referencing it.
More Information:
In Python, a method without a defined return will always return None.
As you are not making the request, no return value is being obtained and so you are seeing none displayed.
Code Fix:
You need to execute the request like so:
service.people().searchContacts(pageSize=10, query="A", readMask="names").execute()
Also, the response object has no property body, so you will need to use
print(request.results)
to view the response text.

Need a Python script for Slack to deactivate a user [duplicate]

I have tried multiple approaches to this. Tried first getting the user without any user id - this returns me just my user, then tried getting user with other id's and it also retrieves data correctly. However, I can't seem to be able to set user attribute 'deleted'. i'm using this python approach.
slack_client.api_call('users.profile.set', deleted=True, user='U36D86MNK')
However I get the error message of:
{u'error': u'invalid_user', u'ok': False}
Maybe someone has already done this? It says in documentation that it's a paid service mentioning this message under a user property:
This argument may only be specified by team admins on paid teams.
But shouldn't it give me a 'paid service' response in that case then?
The users.profile.set apparently does not work for for setting each and every property of a user.
To set the deleted property there is another API method called users.admin.setInactive. Its an undocumented method and it will only work on paid teams.
Note: This requires a legacy token and doesn't work with App tokens - these are only available on paid plans and new legacy tokens can't be created anymore
in python you can do the following:
import requests
def del_slack_user(user_id): # the user_id can be found under get_slack_users()
key = 'TOKEN KEY' #replace token key with your actual token key
payload = {'token': key, 'user': user_id}
response = requests.delete('https://slack.com/api/users.admin.setInactive', params=payload)
print(response.content)
def get_slack_users():
url = 'https://slack.com/api/users.list?token=ACCESSTOKEN&pretty=1'
response = requests.get(url=url)
response_data = response.json() # turns the query into a json object to search through`
You can use Slack's SCIM API to enable and disable a user. Note that, as with the undocumented API endpoint mentioned in other answers this requires a Plus/Enterprise account.

How can I find follow requested users with python-twitter

I am trying to follow some user in a list with python-twitter library. But I am taking "You've already requested to follow username" error for some users. That means I have sent a following request to that user so I cant do that again. So how can I control users, I sent following request. Or is there other way to control it.
for userID in UserIDs:
api.CreateFriendship(userID)
EDIT: I am summerizing: You can follow some users when you want. But some ones don't let it. Firstly you must send friendship request, then he/she might accept it or not. What I want to learn is, how I can list requested users.
You have two options here:
call GetFriends before the loop:
users = [u.id for u in api.GetFriends()]
for userID in UserIDs:
if userID not in users:
api.CreateFriendship(userID)
use try/except:
for userID in UserIDs:
try:
api.CreateFriendship(userID)
except TwitterError:
continue
Hope that helps.
It has been close to three years since this question was asked but responding for reference as it shows up as the top hit when you Google the issue.
As of this post, this is still the case with python-twitter (i.e. there is no direct way with python-twitter to identify pending friendship or follower requests).
That said, one can extend the API class to achieve it. An example is available here: https://github.com/itemir/twitter_cli
Relevant snippet:
class ExtendedApi(twitter.Api):
'''
Current version of python-twitter does not support retrieving pending
Friends and Followers. This extension adds support for those.
'''
def GetPendingFriendIDs(self):
url = '%s/friendships/outgoing.json' % self.base_url
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data.get('ids',[])
def GetPendingFollowerIDs(self):
url = '%s/friendships/incoming.json' % self.base_url
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data.get('ids',[])

Create a cookie that lasts until the browser is closed(Session Cookie?)

I am familiar with assigning, creating cookies in Python. But I am unsure how to create a cookie that will last until the current browser session is closed(so I have a very rudimentary way of telling when the user is returning to my website).
So which cookie header do I set to make sure the cookie will expire/delete when the browser is closed in Python? Do I use the SimpleCookie object or another object for this?
This thread says I set the cookie_lifetime flag/header in PHP, but what about for python? http://bytes.com/topic/php/answers/595383-how-declare-cookie-will-destroy-after-browser-closed
Would this create a cookie that expires on closing of the browser?
cookie = Cookie.SimpleCookie()
cookie["test"] = "MYTEST"
cookie["test"]['expires'] = 0 # or shd I set the max-age header instead?
print str(cookie) + "; httponly"
Just leave out the "expires" value altogether, i.e. don't set it to anything. See the Wikipedia entry for details:
Set-Cookie: made_write_conn=1295214458; path=/; domain=.foo.com
[...]
The second cookie made_write_conn does not have expiration date, making it a session cookie. It will be deleted after the user closes his/her browser
In Python:
In [11]: from Cookie import SimpleCookie
In [12]: c = SimpleCookie()
In [13]: c['test'] = 'MYTEST'
In [14]: print c
Set-Cookie: test=MYTEST
Mack,
Your answer looks correct to me. Setting "expires" = 0 on the Morsel object should do what you want. Have you tested it?
Looks like max-age is not supported by IE:
http://mrcoles.com/blog/cookies-max-age-vs-expires/

Categories