2019-03-31 16:01:50 Python

Python

Copy Copied! Full
from flask import Flask, redirect,url_for, session, request, render_template from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from werkzeug.utils import secure_filename from flask_login import UserMixin, LoginManager, login_user, logout_user, current_user from datetime import datetime #from requests_oauthlib import OAuth1Service from rauth import OAuth1Service import random, string, config app = Flask(__name__) app.secret_key = '***********************' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://localhost/flasknote" db = SQLAlchemy(app) login_manager = LoginManager(app) login_manager.login_view = 'index' migrate = Migrate(app, db) CONSUMER_KEY = config.ConsumerKey CONSUMER_SECRET = config.ConsumerSecretKey ACCESS_TOKEN = config.AccessToken ACCESS_SECRET = config.AccessSecretToken service = OAuth1Service( name='twitter', consumer_key='CONSUMER_KEY', consumer_secret='CONSUMER_SECRET', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/authorize', authorize_url='https://api.twitter.com/oauth/access_token', base_url='https://api.twitter.com/1.1/' ) class user2(UserMixin, db.Model): #userテーブルクラス __tablename__ = 'user2' #カラム定義 id = db.Column(db.String(10), primary_key=True) username = db.Column(db.String(64), index=True) description = db.Column(db.String(1024), index=True) user_image_url = db.Column(db.String(1024), index=True) date_puvlished = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) twitter_id = db.Column(db.String(64), nullable=False, unique=True) def __repr__(self): return '<user2 %r>' % self.username # def init_db(app): # db.init_app(app) # Migrate(app, db) # @app.route('/') # def index(): # users = user2.query.all() # return render_template('index4.html', users=users) @app.route('/') def index(): return render_template('index.html') @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/oauth/twitter') def oauth_authorize(): if not current_user.is_anonymous: return redirect(url_for('index')) else: request_token = service.get_request_token( params={'oauth_callback': url_for('oauth_callback', provider='twitter', _external=True)}) session['request_token'] = request_token return redirect(service.get_authorize_url(request_token[0])) @app.route('/oauth/twitter/callback') def oauth_callback(): request_token = session.pop('request_token') oauth_session = service.get_auth_session( request_token[0], request_token[1], data={'oauth_verifier':request.args['oauth_verifier']}) profile = oauth_session.get('account/verify_credentials.json').json() twitter_id = str(profile.get('id')) username = str(profile.get('name')) description = str(profile.get('description')) profile_image_url = str(profile.get('profile_image_url')) user = db.session.query(user2).filter(user2.twitter_id==twitter_id).first() if user: user.twitter_id = twitter_id user.username = username else: user = user2(twitter_id = twitter_id, usernames=username, user_image_url=profile_image_url) db.session.add(user) db.session.commit() # このユーザー情報を元にセッションを生成 login_user(user, True) return redirect(url_for('index')) @login_manager.user_loader def load_user(id): return user2.query.get(int(id)) @app.route('/form') def form(): return render_template('form4.html') @app.route('/home') def home(): return render_template('home.html') @app.route('/register', methods=['POST']) def register(): if request.form['username'] and request.form['description'] and request.files['image']: f = request.files['image'] filepath = 'static/' + secure_filename(f.filename) f.save(filepath) filepath = '/' + filepath randomId = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) #あたらしいuserをinsert newUser2 = user2(id=randomId, username=request.form['username'], description=request.form['description'], user_image_url=filepath) db.session.add(newUser2) db.session.commit() return render_template('result.html', username=request.form['username'], description=request.form['description']) else: return render_template('error.html') @app.cli.command('initdb') def initdb_command(): db.create_all() if __name__ == '__main__': app.run(debug=True)
RECOMMEND