I need help with a question I have in mind.I've been working on big data and machine learning lately.I'm going to do some work on twitter data first, but I don't want my work to remain only on the terminal screen.I want to see the data on the web, is it possible using flask or django?It doesn't have to be just twitter data, as I said at first, it could be any data.
For Example: I want to build a structure like this
from twython import Twython
CONSUMER_KEY = '***'
CONSUMER_SECRET = '***'
ACCESS_TOKEN = '***'
ACCESS_TOKEN_SECRET = '***'
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET,
ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
user = twitter.get_user_timeline(screen='jack')
print(user[0]['user']['friends_count'])
print(user[0]['user']['statuses_count'])
print(user[0]['user']['favourites_count'])
How do I use this code structure in django or flask? If I write this in a class, if I call it in django or flask, do I do a proper job?
Short answer yes, all kind of python function will work.
Flask and Django will help you to create either API or web interface. For this, you need a web server. Here are things that you need to look while using your any function in these frameworks.
Install a web server
Install Django or Flask
Integrate Web server with installed application
Define Entry point for your request. ex www.abc.com/landing_page for this you need to create a host on your system www.abc.com when this points to your application then define a route landing_page so it will handle the incoming request.
Then check how Django and Flask handle these request and define request handler
After handling these request finally call your function in the request handler
Final if API return response in JSON, TEXT or any other format else showing web page then call desired template and display page.
Related
I built a web app using Django and the wrapper for the Spotify api, Spotipy, and deployed it to Heroku. The problem I am facing is that the redirect uri opens on the machine running the code, which in this case is the linux server used by heroku. Because of this, the user never actually sees the page prompting them to authenticate the app and login to their Spotify accounts, resulting in a request timeout from Heroku. This happens when my REDIRECT_URI is set to http://localhost/. I have tried to set the REDIRECT_URI to https://nameofmyapp.herokuapp.com which then resulted in an EOFError from the Spotipy module. I have not been able to find a solution for this. For context, my authentication flow is set up as follows:
def index(request):
cache_handler = spotipy.DjangoSessionCacheHandler(request=request)
auth_manager = spotipy.oauth2.SpotifyOAuth(
env("CLIENT_ID"), env("CLIENT_SECRET"), env("REDIRECT_URI"), scope=env("SCOPE"), cache_handler=cache_handler)
session = spotipy.Spotify(
oauth_manager=auth_manager, requests_session=True)
I'm trying to get this example to work from https://github.com/ozgur/python-linkedin. I'm using his example. When I run this code. I don't get the RETURN_URL and authorization_code talked about in the example. I'm not sure why, I think it is because I'm not setting up the HTTP API example correctly. I can't find http_api.py, and when I visit http://localhost:8080, I get a "this site can't be reached".
from linkedin import linkedin
API_KEY = 'wFNJekVpDCJtRPFX812pQsJee-gt0zO4X5XmG6wcfSOSlLocxodAXNMbl0_hw3Vl'
API_SECRET = 'daJDa6_8UcnGMw1yuq9TjoO_PMKukXMo8vEMo7Qv5J-G3SPgrAV0FqFCd0TNjQyG'
RETURN_URL = 'http://localhost:8000'
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
#authorization.state = 'your_encoded_message'
print authentication.authorization_url # open this url on your browser
application = linkedin.LinkedInApplication(authentication)
http_api.py is one of the examples provided in the package. This is an HTTP server that will handle the response from LinkedIn's OAuth end point, so you'll need to boot it up for the example to work.
As stated in the guide, you'll need to execute that example file to get the server working. Note you'll also need to supply the following environment variables: LINKEDIN_API_KEY and LINKEDIN_API_SECRET.
You can run the example file by downloading the repo and calling LINKEDIN_API_KEY=yourkey LINKEDIN_API_SECRET=yoursecret python examples/http_api.py. Note you'll need Python 3.4 for it to work.
My Django application uses an API which is a SOAP service. I'm currently using a python SOAP/WSDL client called SUDS. In order to use the API, I have to initialize the client and provide it with a link to the endpoint, login, API key, and password.
Simplified code that does it:
from suds.client import Client
client = Client('link.to.WSDL.endpoint')
session_id = client.service.a_log_in_service('api_key', 'login', 'password')
# the session_id is required by all other 'client.service.xxx' services
Everything works just fine, although it takes some time to initialize the client.
Now, every time I want to send a request to the API in a view, I have to initialize the client. I can't see any way to "share" the already initialized client among many views. It would be great to have the client up and running somewhere, so that any user can send an API request using it.
Once I've done the log in in a view, I can store the session_id (in a session, db, file) and use it in other views, but the client still needs to be initialized over again, which means downloading the 200-KB XML file.
Having to download 200 KB every time a user hits a button seems not right at all.
Thanks in advance!
I created 2 applications in my Azure directory, 1 for my API Server and one for my API client. I am using the Python ADAL Library and can successfully obtain a token using the following code:
tenant_id = "abc123-abc123-abc123"
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token = context.acquire_token_with_username_password(
'https://myapiserver.azurewebsites.net/',
'myuser',
'mypassword',
'my_apiclient_client_id'
)
I then try to send a request to my API app using the following method but keep getting 'unauthorized':
at = token['accessToken']
id_token = "Bearer {0}".format(at)
response = requests.get('https://myapiserver.azurewebsites.net/', headers={"Authorization": id_token})
I am able to successfully login using myuser/mypass from the loginurl. I have also given the client app access to the server app in Azure AD.
Although the question was posted a long time ago, I'll try to provide an answer. I stumbled across the question because we had the exact same problem here. We could successfully obtain a token with the adal library but then we were not able to access the resource I obtained the token for.
To make things worse, we sat up a simple console app in .Net, used the exact same parameters, and it was working. We could also copy the token obtained through the .Net app and use it in our Python request and it worked (this one is kind of obvious, but made us confident that the problem was not related to how I assemble the request).
The source of the problem was in the end in the oauth2_client of the adal python package. When I compared the actual HTTP requests sent by the .Net and the python app, a subtle difference was that the python app sent a POST request explicitly asking for api-version=1.0.
POST https://login.microsoftonline.com/common//oauth2/token?api-version=1.0
Once I changed the following line in oauth2_client.py in the adal library, I could access my resource.
Changed
return urlparse('{}?{}'.format(self._token_endpoint, urlencode(parameters)))
in the method _create_token_url, to
return urlparse(self._token_endpoint)
We are working on a pull request to patch the library in github.
For the current release of Azure Python SDK, it support authentication with a service principal. It does not support authentication using an ADAL library yet. Maybe it will in future releases.
See https://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html#authentication for details.
See also Azure Active Directory Authentication Libraries for the platforms ADAL is available on.
#Derek,
Could you set your Issue URL on Azure Portal? If I set the wrong Issue URL, I could get the same error with you. It seems that your code is right.
Base on my experience, you need add your application into Azure AD and get a client ID.(I am sure you have done this.) And then you can get the tenant ID and input into Issue URL textbox on Azure portal.
NOTE:
On old portal(manage.windowsazure.com),in the bottom command bar, click View Endpoints, and then copy the Federation Metadata Document URL and download that document or navigate to it in a browser.
Within the root EntityDescriptor element, there should be an entityID attribute of the form https://sts.windows.net/ followed by a GUID specific to your tenant (called a "tenant ID"). Copy this value - it will serve as your Issuer URL. You will configure your application to use this later.
My demo is as following:
import adal
import requests
TenantURL='https://login.microsoftonline.com/*******'
context = adal.AuthenticationContext(TenantURL)
RESOURCE = 'http://wi****.azurewebsites.net'
ClientID='****'
ClientSect='7****'
token_response = context.acquire_token_with_client_credentials(
RESOURCE,
ClientID,
ClientSect
)
access_token = token_response.get('accessToken')
print(access_token)
id_token = "Bearer {0}".format(access_token)
response = requests.get(RESOURCE, headers={"Authorization": id_token})
print(response)
Please try to modified it. Any updates, please let me know.
I use Django-social-auth to authenticate the users of a Django project. So I guess I have all the necessary information about a Twitter user to make a post on their behalf on their Twitter account. So do I really need to install a new app? or with the info at hand how would I do that? Isn't it just a matter of posting to a Twitter API with the relevant info?
You could just extract the code into your own project and that will work. But the benefits of using an open source library is that there's a good chance when Twitter or Social Network X changes it's API, the library, if popular, would get updated as opposed to you needing to make the change.
So if you use Django Social Auth you can do:
import urllib
import settings
import oauth2 as oauth
try:
twitter_user = user.social_auth.get(provider='twitter')
except:
return
if not twitter_user.tokens:
return
access_token = twitter_user.tokens['oauth_token']
access_token_secret = twitter_user.tokens['oauth_token_secret']
token = oauth.Token(access_token,access_token_secret)
consumer_key = settings.TWITTER_CONSUMER_KEY
consumer_secret = settings.TWITTER_CONSUMER_SECRET
consumer = oauth.Consumer(consumer_key,consumer_secret)
client = oauth.Client(consumer,token)
data = {'status':'Your tweet goes here'}
request_uri = 'https://api.twitter.com/1/statuses/update.json'
resp, content = client.request(request_uri, 'POST', urllib.urlencode(data))
Yes, I believe if you have the User's twitter account details that are necessary, then you can write an (django) app which will do so. You can use something like python-twitter to post to twitter.
You should be able to find more information regarding Twitter's api here.