我运行一个脚本,将图像转换为PDF文件,并将PDF保存在本地,它在我的Windows机器上工作,但在我的 flask 服务器上,他们没有保存。
以下是代码
from cmath import e
from os import link
from pickle import GET
from webbrowser import get
from flask import Flask, render_template, request, jsonify , redirect, url_for
from flask import send_file
import json
import requests
from libgen_api import LibgenSearch
from kissmanga import get_search_results, get_manga_details, get_manga_episode, get_manga_chapter
import aiohttp
import aiofiles
import asyncio
import os
from fake_headers import Headers
from fpdf import FPDF
from PIL import Image
import glob
import uuid
app = Flask(__name__)
@app.route("/")
def home():
return render_template(
"index.html"
)
@app.route("/api/default")
def titleSearch():
try:
title = request.args.get('query')
s = LibgenSearch()
results = s.search_title(title)
item_to_download = results[0]
download_links = s.resolve_download_links(item_to_download)
return render_template(
"results.html", results=results, download_links=download_links, title=title, )
except IndexError:
return render_template(
"error.html")
@app.route("/api/manga")
def mangasearch():
try:
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
InputMangaTitle = request.args.get('manganame')
InputMangaCh = request.args.get('mangach')
path = os.path.dirname(os.path.realpath(__file__))
os.chdir(path)
if os.path.exists('temp') == False:
os.makedirs('temp')
if os.path.exists('PDFs') == False:
os.makedirs('PDFs')
manga_search = get_search_results(query=InputMangaTitle)
for k in manga_search:
try:
titleManga=(k.get('title' ))
except AttributeError as attErr:
print(f'{bcolors.FAIL}Query did not yield any results!{bcolors.ENDC}')
quit()
for k in manga_search:
IdManga=(k.get('mangaid' ))
mangaChNum= InputMangaCh
# for k in manga_search:
# print(titleManga)
manga_chapter = get_manga_chapter(mangaid=IdManga, chapNumber=mangaChNum)
pdfName = titleManga+' ch.# '+ mangaChNum
global FileName
FileName = pdfName
# print(manga_chapter)
async def fetch(session, url):
try:
url = url[1:-1]
async with session.get(url) as resp:
fileNameNE = (url.split('/')[-1]).split('.')[0]
fileName = fileNameNE+'.jpg'
fullFileName = 'temp/'+fileName
if resp.status == 200:
async with aiofiles.open(fullFileName, mode='wb') as f:
await f.write(await resp.read())
await f.close()
print(f'{bcolors.OKGREEN}Done: {bcolors.ENDC}{url}')
return fullFileName
else:
print(f'{bcolors.WARNING}Rejected URL: {url} | Status: {resp.status}{bcolors.ENDC}')
except Exception as err:
print(err)
async def main(image_urls):
tasks = []
headers = Headers(headers=True).generate()
async with aiohttp.ClientSession(headers=headers) as session:
for image in image_urls:
coroutineTask = asyncio.ensure_future(fetch(session, image))
tasks.append(coroutineTask)
data = await asyncio.gather(*tasks)
return data
def pdfGen(imageList):
pdf = FPDF()
for image in imageList:
if image == None:
continue
cover = Image.open(image)
width, height = cover.size
width, height = float(width * 0.264583), float(height * 0.264583)
pdf_size = {'P': {'w': 210, 'h': 297}, 'L': {'w': 297, 'h': 210}}
orientation = 'P' if width < height else 'L'
width = width if width < pdf_size[orientation]['w'] else pdf_size[orientation]['w']
height = height if height < pdf_size[orientation]['h'] else pdf_size[orientation]['h']
pdf.add_page(orientation=orientation)
pdf.image(image, 0, 0, width, height)
pdf.output(f"PDFs/{pdfName}.pdf", "F")
print(f'{bcolors.OKCYAN}Generated PDF: {pdfName}.pdf {bcolors.ENDC}')
if __name__ == "__main__":
try:
image_urls = (manga_chapter['totalPages']).strip('][').split(', ')
result = asyncio.run(main(image_urls))
pdfGen(result)
files = glob.glob('temp/*')
for f in files:
os.remove(f)
except Exception as e:
print(e)
return render_template("manga.html", pdfName = pdfName)
except IndexError:
return render_template(
"error.html")
@app.route('/return-files/')
def return_files_tut():
try:
return send_file(f'PDFs/{FileName}.pdf')
except Exception as e:
return str(e)
if __name__ == "__main__":
app.run(debug=False, port=80)
正如你所看到的,它应该保存PDF在PDF/{pdfName}.pdf中,但当试图发送文件时,它说它不在那里
我尝试更改文件路径,但没有成功。
1条答案
按热度按时间vdgimpew1#
如果你只是把你的脚本复制到一个Flask应用程序中,它是不会工作的。根据环境调整你的代码,它就会工作。
您应该关注
if __name__ == '__main__':
线。这在您的路线中没有意义。阅读here以获得更多信息。下面的示例使用Flask's async extra,应该可以满足您的需要。
用户可以通过输入标题来搜索出版物。如果他选择了一个标题,则可能的章节将以PDF格式提供以供下载。如果选择了一个章节进行下载,则处理过程基本上与您的规范相对应。将创建一个临时目录,可用的图像将下载到该目录中。您有两种方法可供选择:取决于您要创建目录的位置和方式。一旦加载了所有图像,将根据它们的路径信息生成一个PDF,该PDF直接从内存中传送。然后删除使用的目录。
flask
HTML(./模板/索引. html)
HTML(./模板/情节. html)