hug create GET endpoint to download created word document - python

I'm working with Python hug API would like to create a GET API for the frontend. The frontend can download a created word document file e.g. via download button. However, after going through a documentation, I still cannot figure out a way to do it.
Here is my working script so far:
import os
import hug
from docx import Document
#hug.get("/download_submission_document")
def download_submission_document():
file_name = 'example.docx'
document = Document()
document.add_heading('Test header', level=2)
document.add_paragraph('Test paragraph')
document.save(file_name)
# TO DO: send a created file to frontend
I'm not sure if we can send the object right away or we have to save it first somewhere before sending the the frontend. (requirements: hug, python-docx)
I'm trying to use something like
#hug.get("/download_submission_document", output=hug.output_format.file)
but not sure how to return a file.

Alright, I found a solution which is easier than I thought. Just do the following:
#hug.get("/download_submission_document", output=hug.output_format.file)
def download_submission_document():
file_name = 'example.docx'
document = Document()
document.add_heading('Test header', level=2)
document.add_paragraph('Test paragraph')
document.save(file_name)
return file_name
Return file_name already download the docx

Related

Download GitLab file with gitlab-python

I am trying to download a file or folder from my gitlab repository, but they only way I have seen to do it is using CURL and command line. Is there any way to download files from the repository with just the python-gitlab API? I have read through the API and have not found anything, but other posts said it was possible, just gave no solution.
You can do like this:
import requests
response = requests.get('https://<your_path>/file.txt')
data = response.text
and then save the contents (data) as file...
Otherwise use the API:
f = project.files.get(path='<folder>/file.txt',ref='<branch or commit>')
and then decode using:
import base64
content = base64.b64decode(f.content)
and then save content as file...

How do I allow users to download a MIDI file with Flask without getting a 0 byte download?

I am writing an application that creates a midi file using the MIDIUtil library. When the user submits an HTML form, a midi file object is created with MIDIUtil. How do I allow the user to download this as a .mid file? I have tried the following code, but I end up downloading a file of 0 bytes.
return Response(myMIDIFile, mimetype='audio/midi')
I use a variant of the following code to allow my users to download images they generate. The below code should work for you. Please note that you will most likely need to specify the full server path to the file being downloaded.
from flask import send_file
download_filename = FULL_PATH_TO_YOUR_MIDI_FILE
return(send_file(filename_or_fp = download_filename,mimetype="audio/midi",as_attachment=True))
I ended up using this, and it worked.
new_file = open('test.mid', 'wb')
myMIDI.writeFile(new_file)
new_file.close()
new_file = open('test.mid', 'rb')
return send_file(new_file, mimetype='audio/midi')
Might want to just try using send_file
from flask import send_file
return send_file("yourmidifile.mid", as_attachement=True, mimetype="audio\midi")

Python script to save webpage and rename it while saving (save as - command)

Hi I searched a lot and ended up with no relevant results on how to save a webpage using python 2.6 and renaming it while saving.
Better user requests libraty:
import requests
pagelink = "http://www.example.com"
page = requests.get(pagelink)
with open('/path/to/file/example.html', "w") as file:
file.write(page.text)
You may want to use the urllib(2) package to access the webpage, and then save the file object to the desired location (os.path).
It should look something like this:
import urllib2, os
pagelink = "http://www.example.com"
page = urllib2.urlopen(pagelink)
with open(os.path.join('/(full)path/to/Documents',pagelink), "w") as file:
file.write(page)

python-docx: add picture from the web

I am using python-docx with django to generate word documents.
Is there a way to use add_picture to add an image from the web rather then from the file system?
In word, when I select to add a picture, I can just give the URL.
I tried to simply so the same and write:
document.add_picture("http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg")
and got error:
IOError: [Errno 22] invalid mode ('rb') or filename:
'http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg'
Not very elegant, but i found a solution, based on the question in here
my code now looks like that:
import urllib2, StringIO
image_from_url = urllib2.urlopen(url_value)
io_url = StringIO.StringIO()
io_url.write(image_from_url.read())
io_url.seek(0)
try:
document.add_picture(io_url ,width=Px(150))
and this works fine.
If you use docxtemplater (command line interface),
you can create your own templates and embed images with a URL.
See : https://github.com/edi9999/docxtemplater
docxtemplater command line interface
docxtemplater image replacing
Below is a fresh implementation for Python 3:
from io import BytesIO
import requests
from docx import Document
from docx.shared import Inches
response = requests.get(your_image_url) # no need to add stream=True
# Access the response body as bytes
# then convert it to in-memory binary stream using `BytesIO`
binary_img = BytesIO(response.content)
document = Document()
# `add_picture` supports image path or stream, we use stream
document.add_picture(binary_img, width=Inches(2))
document.save('demo.docx')

Using Google App Engine how to upload document in google docs (python)

I want to upload document, file to google docs using Google Apps Engine (python)
any code or link will be appreciated
See the documentation, but you might try something like:
ms = gdata.MediaSource(file_path='/path/to/your/test.doc', content_type=gdata.docs.service.SUPPORTED_FILETYPES['DOC'])
entry = gd_client.Upload(ms, 'MyDocTitle')
print 'Document now accessible online at:', entry.GetAlternateLink().href
Solution is with files Upload, You need to read data using below line in python:
function to read file size
def getSize(self,fileobject):
fileobject.seek(0,2) # move the cursor to the end of the file
size = fileobject.tell()
return size
f = self.request.POST.get('fname').file
media = gdata.data.MediaSource(file_handle=f.read(), content_type=gdata.docs.service.SUPPORTED_FILETYPES[ext], content_length=self.getSize(self.request.POST.get('fname').file))
And also need to modify the gdata python library of Google to achieve this:
client.py:
in
def upload_file
replace:
while not entry:
entry = self.upload_chunk(start_byte, self.file_handle.read(self.chunk_size))
start_byte += self.chunk_size
With:
while not entry:
entry = self.upload_chunk(start_byte, self.file_handle)
start_byte += self.chunk_size
And you can upload file directory to google doc

Categories

Resources