instaupload / app.py
nagasurendra's picture
Update app.py
67f580a verified
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
import os
from werkzeug.utils import secure_filename
from instagrapi import Client
from PIL import Image
import time
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# Ensure upload folder exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Instagram credentials (replace with your own)
INSTAGRAM_USERNAME = ""
INSTAGRAM_PASSWORD = ""
# Initialize instagrapi client
cl = Client()
cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_image():
if 'image' not in request.files:
flash('No file part')
return redirect(url_for('index'))
file = request.files['image']
if file.filename == '':
flash('No file selected')
return redirect(url_for('index'))
if file:
filename = secure_filename(f"captured_{int(time.time())}.jpg")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Convert to JPEG if needed (Instagram requires JPEG)
img = Image.open(filepath)
if img.format != 'JPEG':
img = img.convert('RGB')
img.save(filepath, 'JPEG')
try:
# Upload to Instagram
cl.photo_upload(
path=filepath,
caption="Uploaded from Flask Camera App"
)
flash('Image uploaded to Instagram successfully!')
except Exception as e:
flash(f'Error uploading to Instagram: {str(e)}')
# Clean up
os.remove(filepath)
return redirect(url_for('index'))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')