How to display images in html? - python

I have a working app using the imgur API with python.
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
for item in items:
print(item.link)
It outputs a set of imgur links. I want to display all those pictures on a webpage.
Does anyone know how I can integrate python to do that in an HTML page?

OK, I haven't tested this, but it should work. The HTML is really basic (but you never mentioned anything about formatting) so give this a shot:
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
htmloutput = open('somename.html', 'w')
htmloutput.write("[html headers here]")
htmloutput.write("<body>")
for item in items:
print(item.link)
htmloutput.write('SOME DESCRIPTION<br>')
htmloutput.write("</body</html>")
htmloutput.close
You can remove the print(item.link) statement in the code above - it's there to give you some comfort that stuff is happening.
I've made a few assumptions:
The item.link returns a string with only the unformatted link. If it's already in html format, then remove the HTML around item.link in the example above.
You know how to add an HTML header. Let me know if you do not.
This script will create the html file in the folder it's run from. This is probably not the greatest of ideas. So adjust the path of the created file appropriately.
Once again, though, if that is a real client secret, you probably want to change it ASAP.

Related

create email with python

im working in a personal project that needs new email in the start, and i want create a new email with python also i don't want run a complicate smtp server(I don't know much about that yet) i want do something like temp mail with api, i'd tried temp mail api but i got error i do something like this
import requests
url = "privatix-temp-mail-v1.p.rapidapi.com/request/mail/id/md5 of my temp mail"
req = request.get(url)
print(req)
but i got 401 status code that says your api key is invalid
then i go to rapidapi website and see examples there was a header for req so i put that to my code that was like:
import requests
url = "https://privatix-temp-mail-v1.p.rapidapi.com/request/mail/id/md5"
headers = {
'x-rapidapi-host': "privatix-temp-mail-v1.p.rapidapi.com",
'x-rapidapi-key': "that was a key"
}
req = request.get(url, headers=headers)
then i got this
{"message":"You are not subscribed to this API."}
now i get confused and i don't know what is problem if you know temp mail api or something liks this service or any suggest pls help me
In order to use any API from RapidAPI Hub, you need to subscribe to that particular API. It's pretty simple.
Go to the Pricing Page of this API and choose a plan according to your need. Click on the subscribe button and you will be good to go. However, the Basic plan is free but a soft limit is associated with it so it may ask for your card details.

How to change email signature using GMAIL API?

I want to setup email signature for each user in the domain. The thing is I already have a html signature ready but I dont know how to use html signature with GMAIl API. I am using python and when I try to do that, it only converts it to text. Is there any way to embed html signature in a variable which then inserts into the gmail account using GMAIl API?
I recommend checking the documentation Managing signatures
primary_alias = None
aliases = gmail_service.users().settings().sendAs().\
list(userId='me').execute()
for alias in aliases.get('sendAs'):
if alias.get('isPrimary'):
primary_alias = alias
break
sendAsConfiguration = {
'signature': 'I heart cats'
}
result = gmail_service.users().settings().sendAs().\
patch(userId='me',
sendAsEmail=primary_alias.get('sendAsEmail'),
body=sendAsConfiguration).execute()
print 'Updated signature for: %s' % result.get('displayName')
The documentation states it should be HTML
Thanks for the reply. I found the solution to use html signatures. What I did is created html files using python script (You can also create them in any other way. I just did using python because I wanted a single script to create a html signature as well as change the email signature for the user).
And then imported whole html as text inside a python variable as shown below.
file = open(test.html, 'r')
htmlfile = file.read()
ESignature = {'signature': htmlfile}
After that in the email signature body parameter I just used the variable where I stored the html signature and it worked.
sig = service.users().settings().sendAs().update(userId='me', sendAsEmail="test#example.org", body=ESignature).execute()

Python requests on Instagram media link returns Not Found error

I have this function in Python to get media id of the post from its URL provided:
def get_media_id(self):
req = requests.get('https://api.instagram.com/oembed/?url={}'.format(self.txtUrl.text()))
media_id = req.json()['media_id']
return media_id
When I open the result URL in the browser it returns data but in the code the result is "404 not found"
For example consider this link:
https://www.instagram.com/p/B05bitzp15CE8e3Idcl4DAb8fjsfxOsSUYvkDY0/
When I put it in the url the result is:
But when I run the same in this function it returns 404 error
I tried running your code and assuming that self.txtUrl.text() there is nothing wrong with your code. The problem is that you are trying to get access to a media id of a private account without the access token.
The reason that you are able to open that link in the browser is due to the fact that you are likely logged into that account or are following it. To use the method you have given, you would need a public instagram post, for example try setting txtUrl.text() = https://www.instagram.com/p/fA9uwTtkSN/. Your code should work just fine.
The problem is that your GET request doesn't have any authorisation token to gain access to the post. Other people have written answers to how to get the media_id if you have the access token here: Where do I find the Instagram media ID of a image (having access token and following the image owner)?

Google Drive API v3 updating a file on the go (using realtime data) in python

I am trying to update a file that I created with some new data. Essentially, i am trying to append contents to an already created file. I have tried different ways using different attributes but nothing seems to work so far. The migration from v2 to v3 seems to have made things harder to develop in python.
This is my code so far
def updateFile(fileID, contents):
credentials = get_credentials() #this function gets the credentials for oauth
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
# First retrieve the file from the API.
#fileCreated = service.files().get(fileId=fileID).execute()
#print(dir(fileCreated.update()))
# File's new content.
file_metadata = { 'name' : 'notes.txt', 'description' : 'this is a test' }
fh = BytesIO(contents.encode())
media = MediaIoBaseUpload(fh,
mimetype='text/plain')
# Send the request to the API.
#print(BytesIO(contents.encode()).read())
print(fileID)
updated_file = service.files().update(
body=file_metadata,
#uploadType = 'media',
fileId=fileID,
#fields = fileID,
media_body=media).execute()
I have tried using MediaFileUpload (it works only for uploading a file) but I am appending a 'string' that is real time generated using a voice interface and is not stored in any file. So I ended up using MediaIoBaseUpload.
The code runs without any error, but the file is not updated. Any help is appreciated.
okay, so i figured out what was wrong with my code. Apparently, nothing is wrong with this chunk of code that I posted. I realized that I have not converted the document I created to a "google document" hence the code didnt update the document. I changed the mime type of the document i create to be a google document, and now the code works fine :)
You can also use service.files().get_media(fileId=fileID).execute() to get the file content and append new content to it.

Editing Google docs with drive API

(For clarity, this post relates to the difference between the Google Documents List API and Google Drive API on Google App Engine with Python)
With the [now deprecated] Documents list API I was able to edit Google Documents by exporting as HTML, modifying the HTML and then re-uploading, either as a new document or as a modification to the original. This was useful for things like generating PDF documents from a template. I have been trying to replicate this functionality with the new Drive API (V2), however seem unable to.
Have come up with this ...
http = # authenticated http client
drive_service = build('drive', 'v2', http=http)
# get the file ...
file = drive_service.files().get(fileId=FILE_ID).execute()
# download the html ...
url = file['exportLinks']['text/html']
response, content = http.request(url)
# edit html
html = content.replace('foo', 'bar')
# create new file with modified html ...
body = {'title':'Modified Doc',
'description':'Some description',
'mimeType':'text/html'}
media_body = MediaIoBaseUpload(StringIO.StringIO(html), 'text/html', resumable=False)
drive_service.files().insert(body=body, media_body=media_body)
The above code uploads an html file as a file into Google Drive, rather then rendering the HTML into a Google Document. Fair enough, this makes sense. But how to I get it render as a Google Doc, as I was able to do with the Documents List API?
One other thing - if I set resumable=True it throws the following error on App Engine - '_StreamSlice' has no len(). Couldn't figure out how to get resumable=True to work?
And one last thing - the sample code in the docs uses a MediaInMemoryUpload object, however if you look at the source it is now deprecated, in favour of MediaIoBaseUpload. Should the sample code be updated?!
i suspect the issue is that the default for conversion has changed from true to false. You must explicitly set convert=true on the upload. See https://developers.google.com/drive/v2/reference/files/insert

Categories