如何在Python 2.7.x中生成PDF/HTML文件的下载URL
Got it, let's break this down step by step for Python 2.7.x. Here's how you can generate PDF/HTML files, store them in a specified directory, create a downloadable URL, and send that URL out:
1. Prerequisites
First, if you're generating PDFs, install the reportlab library (it's one of the most reliable options for Python 2.7):
pip install reportlab
For HTML files, no extra libraries are needed—we can write directly to a file.
2. Generate & Save HTML File
Let's start with a simple HTML file. We'll save it to a directory that's accessible by your web server (so users can download it):
import os # Define your target directory (adjust this to your web server's static files path) DOWNLOAD_DIR = "/var/www/html/downloads" # Create directory if it doesn't exist if not os.path.exists(DOWNLOAD_DIR): os.makedirs(DOWNLOAD_DIR) # Generate HTML content html_content = """ <!DOCTYPE html> <html> <head><title>Sample Download</title></head> <body><h1>Hello, this is your downloadable HTML file!</h1></body> </html> """ # Define filename and full path html_filename = "sample_download.html" html_file_path = os.path.join(DOWNLOAD_DIR, html_filename) # Write content to file with open(html_file_path, "w") as f: f.write(html_content.encode("utf-8")) # Handle encoding for Python 2.7 print "HTML file saved to: {}".format(html_file_path)
3. Generate & Save PDF File
Using reportlab to create a basic PDF:
from reportlab.pdfgen import canvas import os DOWNLOAD_DIR = "/var/www/html/downloads" if not os.path.exists(DOWNLOAD_DIR): os.makedirs(DOWNLOAD_DIR) # Define PDF details pdf_filename = "sample_download.pdf" pdf_file_path = os.path.join(DOWNLOAD_DIR, pdf_filename) # Create PDF pdf_canvas = canvas.Canvas(pdf_file_path) pdf_canvas.drawString(100, 750, "Hello, this is your downloadable PDF!") pdf_canvas.drawString(100, 730, "Generated with Python 2.7 & ReportLab") pdf_canvas.save() print "PDF file saved to: {}".format(pdf_file_path)
4. Create a Downloadable URL
Assuming your web server is configured to serve files from /var/www/html/downloads at http://your-domain.com/downloads/, we can build the URL dynamically:
# Your server's base URL (adjust this to your actual domain) BASE_URL = "http://your-domain.com/downloads" # For HTML file html_download_url = "{}/{}".format(BASE_URL, html_filename) print "HTML Download URL: {}".format(html_download_url) # For PDF file pdf_download_url = "{}/{}".format(BASE_URL, pdf_filename) print "PDF Download URL: {}".format(pdf_download_url)
Note: Make sure your web server has read permissions for the DOWNLOAD_DIR and is set up to serve static files from that location.
5. Send the Download URL
Let's use Python's built-in smtplib to send the URL via email. Adjust the SMTP settings to match your email provider (e.g., Gmail, Outlook, or your company's mail server):
import smtplib from email.mime.text import MIMEText def send_download_url(recipient_email, download_url, file_type): # Email configuration sender_email = "your-email@example.com" sender_password = "your-email-password" # For Gmail, use an app password if 2FA is enabled smtp_server = "smtp.example.com" smtp_port = 587 # Typical TLS port # Email content subject = "Your {} Download Link".format(file_type.upper()) body = "Hi there!\n\nYou can download your {} file here: {}\n\nBest regards,\nYour Script".format(file_type, download_url) # Create MIME message msg = MIMEText(body.encode("utf-8"), "plain", "utf-8") msg["Subject"] = subject msg["From"] = sender_email msg["To"] = recipient_email # Send email try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(sender_email, sender_password) server.sendmail(sender_email, recipient_email, msg.as_string()) server.quit() print "Download URL sent to {}".format(recipient_email) except Exception as e: print "Failed to send email: {}".format(str(e)) # Example usage send_download_url("user@example.com", pdf_download_url, "pdf")
Key Notes for Python 2.7
- Always handle string encoding explicitly (use
.encode("utf-8")to avoid Unicode errors) printis a statement, not a function (so no parentheses unless you're printing a single object)- Make sure all file paths are absolute to avoid confusion with working directories
内容的提问来源于stack exchange,提问作者Apurva Kunkulol

