I have three images image1.jpg ,image2.jpg, image3.jpg. I am trying to upload them as a single post. Below is my code:
import facebook
graph = facebook.GraphAPI(oauth_access_token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
file1 = open("image1","rb")
file2 = open('image2', 'rb')
graph.put_photo(file1, 'Look at this cool photo!')
graph.put_photo(file2, 'Look at this cool photo!')
But they get uploaded as separate posts in separate images. How do I upload multiple images in single post?
If someone looking to post Multiple Images or a Video in 2021 using Graph API in Python
import requests
auth_token = "XXXXXXXX"
def postImage(group_id, img):
url = f"https://graph.facebook.com/{group_id}/photos?access_token=" + auth_token
files = {
'file': open(img, 'rb'),
}
data = {
"published" : False
}
r = requests.post(url, files=files, data=data).json()
return r
def multiPostImage(group_id):
imgs_id = []
img_list = [img_path_1, img_path_2]
for img in img_list:
post_id = postImage(group_id ,img)
imgs_id.append(post_id['id'])
args=dict()
args["message"]="Put your message here"
for img_id in imgs_id:
key="attached_media["+str(imgs_id.index(img_id))+"]"
args[key]="{'media_fbid': '"+img_id+"'}"
url = f"https://graph.facebook.com/{group_id}/feed?access_token=" + auth_token
requests.post(url, data=args)
multiPostImage("426563960691001")
same way it work for page, use page_id instead of group_id
Posting a Video
def postVideo(group_id, video_path):
url = f"https://graph-video.facebook.com/{group_id}/videos?access_token=" + auth_token
files = {
'file': open(video_path, 'rb'),
}
requests.post(url, files=files)
First, you have to upload all photos and keep the id's (imgs_id).
Then, make a dict like args, and finally call request method.
imgs_id = []
for img in img_list:
photo = open(img, "rb")
imgs_id.append(api.put_photo(photo, album_id='me/photos',published=False)['id'])
photo.close()
args=dict()
args["message"]="Put your message here"
for img_id in imgs_id:
key="attached_media["+str(imgs_id.index(img_id))+"]"
args[key]="{'media_fbid': '"+img_id+"'}"
api.request(path='/me/feed', args=None, post_args=args, method='POST')
have you tried: put-wall-post ? ..or put-object
put-wall-post might be what you are looking for:
attachment - A dict that adds a structured attachment to the message being posted to the Wall. If you are sharing a URL, you will want to use the attachment parameter so that a thumbnail preview appears in the post. It should be a dict of the form:
Source: http://facebook-sdk.readthedocs.io/en/latest/api.html#api-reference
Related
im trying to create a communication between flutter and a flask rest API. I wanted to send a file from Flutter(epub file) to the API, then process it to txt and finally re-send it to flutter. The problem is that i don't want to create the html box for the uploading part of the file, for ux and ui of the app, so making it easier for the user.
In the server part i use some epub files example in local, so that from chrome i do a get request and all works fine, but i dont know how to upload a file from Flutter app to Flask.
This is the Flask part =
from flask import Flask,send_file,send_from_directory, flash, request, redirect,
url_for
from werkzeug.utils import secure_filename
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
import os
#//////////////////////////////----epub to txt------///////////////////////////////////
def epub2thtml(epub_path):
book = epub.read_epub(epub_path)
chapters = []
for item in book.get_items():
if item.get_type() == ebooklib.ITEM_DOCUMENT:
chapters.append(item.get_content())
print(chapters)
return chapters
blacklist = [ '[document]', 'noscript', 'header', 'html', 'meta', 'head','input', 'script', ]
def chap2text(chap):
output = ''
soup = BeautifulSoup(chap, 'html.parser')
text = soup.find_all(text=True)
for t in text:
if t.parent.name not in blacklist:
output += '{} '.format(t)
return output
def thtml2ttext(thtml):
Output = []
for html in thtml:
text = chap2text(html)
Output.append(text)
return Output
def epub2text(epub_path , nomefile):
chapters = epub2thtml(epub_path)
ttext = thtml2ttext(chapters)
#print (ttext)
a = 0;
s = ' ';
with open(nomefile, 'w') as f:
b = s.join(ttext)
testo = b.split()
for i in testo:
f.write(testo[a])
f.write('\n')
a = a + 1;
print(testo)
f.close()
#//////////////////////////////----server------///////////////////////////////////
app = Flask(__name__)
app.config["CLIENT_EPUB"] = "...../libri"
#app.route('/epub/<string:epubfilename>',methods = ['GET','POST'])
def get_txt(epubfilename):
nometxt = str(os.path.splitext(epubfilename)) + ".txt"
epub2text(epubfilename, nometxt)
try:
return send_from_directory(app.config["CLIENT_EPUB"], nometxt, as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == '__main__':
app.run(debug = True, port=2500)
For the flutter part i wanted to use a multipart request to do some of these requests, an example=
void sendRequest() {
var request = MultipartRequest();
final imagePath = ('assets/testo.txt');
request.setUrl(...url);
request.addFile("text", imagePath);
Response response = request.send();
response.onError = () {
print("Error");
};
response.onComplete = (response) {
print(response);
};
response.progress.listen((int progress) {
print("progress from response object " + progress.toString());
});
}
How can i upload the file from the app to the api without the form and resend it? Thanks in advance, i think it isnt that difficult but i cant!
I have been trying to get spacfic pages extract from each pdf and then merge all the extracted pdf in once.
I have list of pdfs
I am using pdfrw this library but getting error while extracting the pages
from pdfrw import PdfReader, PdfWriter
import os
files = [f for f in os.listdir(
'.') if os.path.isfile(f) and f.endswith('.pdf')]
print(files)
for pdf in files:
pages = PdfReader(pdf).pages
parts = [(6, 7)]
for part in parts:
title = pdf.title().split('.')[0]
outdata = PdfWriter(f'{title}_{part[0]}_.pdf')
for pagenum in range(*part):
outdata.addpage(pages[pagenum-1])
outdata.write()
Please help if possible
raise PdfParseError('Invalid PDF header: %s' %
pdfrw.errors.PdfParseError: Invalid PDF header: '<!doctype html>'
Manas,
One way to achieve your requirement is to use API. For example, consider following code snippet where it splits PDF from uploaded file.
import os
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "*********************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# Source PDF file
SourceFile = ".\\sample.pdf"
# Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
Pages = "1-2,3-"
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
splitPDF(uploadedFileUrl)
def splitPDF(uploadedFileUrl):
"""Split PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["pages"] = Pages
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Split PDF' API request
url = "{}/pdf/split".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Download generated PNG files
part = 1
for resultFileUrl in json["urls"]:
# Download Result File
r = requests.get(resultFileUrl, stream=True)
localFileUrl = f"Page{part}.pdf"
if r.status_code == 200:
with open(localFileUrl, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{localFileUrl}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
part = part + 1
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
with open(fileName, 'rb') as file:
requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" })
return uploadedFileUrl
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
Now, to merge PDF file you can use similar to following code snippet.
import os
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "**********************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# Source PDF files
SourceFile_1 = ".\\sample1.pdf"
SourceFile_2 = ".\\sample2.pdf"
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
UploadedFileUrl_1 = uploadFile(SourceFile_1)
UploadedFileUrl_2 = uploadFile(SourceFile_2)
if (UploadedFileUrl_1 != None and UploadedFileUrl_2!= None):
uploadedFileUrls = "{},{}".format(UploadedFileUrl_1, UploadedFileUrl_2)
mergeFiles(uploadedFileUrls, DestinationFile)
def mergeFiles(uploadedFileUrls, destinationFile):
"""Perform Merge using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["name"] = os.path.basename(destinationFile)
parameters["url"] = uploadedFileUrls
# Prepare URL for 'Merge PDF' API request
url = "{}/pdf/merge".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Get URL of result file
resultFileUrl = json["url"]
# Download result file
r = requests.get(resultFileUrl, stream=True)
if (r.status_code == 200):
with open(destinationFile, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{destinationFile}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
with open(fileName, 'rb') as file:
requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" })
return uploadedFileUrl
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
In this sample I am using pdf.co API. Refer to following links for more information.
https://apidocs.pdf.co/30-pdf-split, https://apidocs.pdf.co/31-pdf-merge
Thanks!
I have written a script that should purchase an asset from catalog.
import re
from requests import post, get
cookie = "blablabla"
ID = 1562150
# getting x-csrf-token
token = post("https://auth.roblox.com/v2/logout", cookies={".ROBLOSECURITY": cookie}).headers['X-CSRF-TOKEN']
print(token)
# getting item details
detail_res = get(f"https://www.roblox.com/library/{ID}")
text = detail_res.text
productId = int(get(f"https://api.roblox.com/marketplace/productinfo?assetId={ID}").json()["ProductId"])
expectedPrice = int(re.search("data-expected-price=\"(\d+)\"", text).group(1))
expectedSellerId = int(re.search("data-expected-seller-id=\"(\d+)\"", text).group(1))
headers = {
"x-csrf-token": token,
"content-type": "application/json; charset=UTF-8"
}
data = {
"expectedCurrency": 1,
"expectedPrice": expectedPrice,
"expectedSellerId": expectedSellerId
}
buyres = post(f"https://economy.roblox.com/v1/purchases/products/{productId}", headers=headers,
data=data,
cookies={".ROBLOSECURITY": cookie})
if buyres.status_code == 200:
print("Successfully bought item")
The problem is that it somehow doesn't purchase any item with error 500 (InternalServerError).
Someone told me that if I add json.dumps() to the script it might work.
How to add json.dumps() here (I don't understand it though I read docs) and how to fix this so the script purchases item?
Big thanks to anyone who can help me.
Import the json package.
json.dumps() converts a python dictionary to a json string.
I'm guessing this is what you want.
buyres =
post(f"https://economy.roblox.com/v1/purchases/products/{productId}",
headers=json.dumps(headers),
data=json.dumps(data),
cookies={".ROBLOSECURITY": cookie})
I found the answer finally, I had to do it like this:
dataLoad = json.dumps(data)
buyres = post(f"https://economy.roblox.com/v1/purchases/products/{productId}", headers=headers,
data=dataLoad,
cookies={".ROBLOSECURITY": cookie})
I am using this API to list users. One of the parameters I could specify is a team id which is placed in an array. When I try to specify a team id it doesn't work when I put it in the payload, but it works when I change the url to include the team id.
This is the API reference: https://api-reference.pagerduty.com/#!/Users/get_users
Here is what I am basing my code off of: https://github.com/PagerDuty/API_Python_Examples/blob/master/REST_API_v2/Users/list_users.py
This is my code when I try to specify team id in the payload. It doesn't work like this for some reason, but it works when I change the url to url = 'https://api.pagerduty.com/users?team_ids%5B%5D=TEAMID&team_ids%5B%5D=' where in TEAMID I have an actual team id.
with open('config/config.json') as f:
config = json.load(f)
API_KEY = config['API_KEY']
TEAM_IDS = ['TEAMID']
def list_users():
url = 'https://api.pagerduty.com/users'
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token={token}'.format(token=API_KEY)
}
payload = {
'team_ids[]': TEAM_IDS
}
r = requests.get(url, headers=headers)
result = []
if r.status_code == 200:
# loops for each user and retrieves their email
result = [user['email'] for user in r.json()['users']]
return result
else:
return None
I want to get this work by listing team id's in the array and sending it in the payload so that I can list more than one team id and not clutter them all in the url.
Looks like you just need something like this
payload = {
'team_ids[]': TEAM_IDS
}
r = requests.get(url, headers=headers, params=payload)
I'm getting a new little problem with API Rest Python between Django and LogicalDOC.
I'm creating a folder inside LogicalDOC, then I would like to save my pdf file inside this new folder taking the folderId.
But, when it seems work because the syntax is good from my point of view : none pdf file appears.
I create a folder, I pick up his ID number : 348930 for example with the command data["id"] and I insert str(data["id"]) in FolderId when I want to save my pdf file in the new folder.
The new folder is created and worked well, but the pdf file is not save inside. Something wrong ?
This is my script :
#login_required
def BirthCertificate_PDF(request, id) :
birthcertificate = get_object_or_404(BirthCertificate, pk=id)
data = {"birthcertificate" : birthcertificate}
template = get_template('BC_raw.html')
html = template.render(Context(data))
filename_directory = str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday)
filename = 'Acte_Naissance_' + filename_directory + '.pdf'
path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename
file = open(path, "w+b")
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8')
file.seek(0)
pdf = file.read()
if pdf :
payload = '{{ "name":"{0}", "parentId":3309569 }}'.format(filename_directory) #Fix parent folder
url = 'http://localhost:8080/services/rest/folder/create'
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
resp = requests.post(url, data=payload, headers=headers, auth=('admin', 'admin'))
rbody = resp.content
data = json.loads(rbody)
print data["id"] #Get ID from the new folder
payload = '{{ "language":"fr","fileName":"{0}","FolderId":'+str(data["id"]) +'}}'.format(filename) #save pdf file inside the new folder thanks to his ID
upfile = path
files = {
'document': (None, payload, 'application/json'),
'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream')
}
url = 'http://localhost:8080/services/rest/document/create'
headers = {'Content-Type': 'multipart/form-data'}
r = requests.post(url, files=files, headers=headers, auth=('admin', 'admin'))
context = {"birthcertificate":birthcertificate,
"path":path}
return render(request, 'BC_PDF.html', context)
file.close()
return HttpResponse(pdf, 'application/pdf')
This is a screen capture which shows that folderID should be : 3538970
This number is also given by : data["id"]
As I said in my comment you don't need to use string concatenation to pass FolderId as payload, just use second argument of format method:
d = '{{ "language":"fr","fileName":"{0}","FolderId":"{1}"}}'.format(filename, str(data["id"]))