簡體   English   中英

Flask和Apache出現API錯誤500

[英]API Error 500 with Flask and Apache

我正在嘗試讓我的API使用Apache在Ubuntu VPS上運行,這是我的FLASK代碼。

#!/usr/bin/env python
import os
from sqlalchemy import update
from flask import Flask, abort, request, jsonify, g, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
import math


# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))
    username = db.Column(db.String(32), index=True)
    password_hash = db.Column(db.String(64))

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expiration=600):
        s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None    # valid token, but expired
        except BadSignature:
            return None    # invalid token
        user = User.query.get(data['id'])
        return user


class Points(db.Model):
    __tablename__ = 'points'
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.String(32))
    username = db.Column(db.String(32))
    shop = db.Column(db.String(64))
    point = db.Column(db.Integer)


class MyPoints(db.Model):
    __tablename__ = 'mypoints'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32))
    shop = db.Column(db.String(64))
    point = db.Column(db.Integer)

class Shops(db.Model):
    __tablename__ = 'shop'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))
    location = db.Column(db.String(32))
    website = db.Column(db.String(32))
    number = db.Column(db.String(32))
    message = db.Column(db.String(32))

@auth.verify_password
def verify_password(username_or_token, password):
    # first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True


@app.route('/api/users/reg', methods=['POST'])
def new_user():
    name = request.json.get('name')
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None or name is None:
        return (jsonify({'status': "Missing fields"}))
        abort(400)    # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        return (jsonify({'status': "Email already Exists"}))
        abort(400)    # existing user
    user = User(username=username, name=name)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'status': "Account Created"}), 201)

@app.route('/api/users/up', methods=['POST'])
def update_password():
    username = request.json.get("username")
    password = request.json.get('password')
    if password is None or username is None:
        return (jsonify({'status': "Missing fields"}))
        abort(400)    # missing arguments
    user = pwd_context.encrypt(password)
    result = db.engine.execute('UPDATE users SET password_hash = "%s" WHERE username = "%s"' % (user, username))

    return (jsonify({'status': "Password Updated"}), 201)

@app.route('/api/users/log', methods=['GET'])
@auth.login_required
def login_user():
    token = g.user.generate_auth_token(600)
    return jsonify({'status': 'Logged in'})

@app.route('/api/users/del', methods=['POST'])
@auth.login_required
def delete_account():
    username = g.user.username
    if username is None:
        return (jsonify({'status': "Missing fields"}))
        abort(400)    # missing arguments

    db.engine.execute("DELETE FROM users WHERE username = '%s'" % username)

    return (jsonify({'status': "Account Deleted"}), 201)




@app.route('/api/points/list', methods=['GET'])
@auth.login_required
def all_points():
    user = g.user.username
    result = MyPoints.query.filter_by(username=user).limit(10).offset(0)

    json_results = []
    for result in result:
      d = {'id': result.id,
           'shop': result.shop,
           'point': result.point,
           'username': result.username}
      json_results.append(d)

    return jsonify(items=json_results)

@app.route('/api/points/<path:shop>', methods=['GET'])
@auth.login_required
def list_points(shop):
    user = g.user.username
    result = MyPoints.query.filter_by(shop=shop).limit(10).offset(0)

    json_results = []
    for result in result:
      d = {'id': result.id,
           'shop': result.shop,
           'point': result.point,
           'username': result.username}
      json_results.append(d)

    return jsonify(items=json_results, )



@app.route('/api/points', methods=['POST'])
@auth.login_required
def update_points():
    date = str(datetime.now())
    username = request.json.get('username')
    shop = request.json.get('shop')
    point = request.json.get('point')
    user = Points(date=date, username=username, shop=shop, point=point)
    db.session.add(user)
    db.session.commit()
    result = db.engine.execute('select point from points WHERE shop == "%s" AND username="%s"' % (shop, username))
    names = []
    for row in result:
        names.append(row[0])
    names = [x.encode('utf-8') for x in names]
    results = map(int, names)
    r = sum(results)
    result = db.engine.execute('UPDATE mypoints SET point = "%s" WHERE username = "%s"' % (r, username))
    return (jsonify({'Points': r}), 201)



if __name__ == '__main__':
    if not os.path.exists('db.sqlite'):
        db.create_all()
    app.run(debug=True)

每當我嘗試運行一個Curl命令時;

curl -i -X POST -H "Content-Type: application/json" -d '{"username":"miguel","password":"python"}' http://adventorious.com/api/users

它拋出;

HTTP/1.1 500 Internal Server Error
Date: Sun, 15 Feb 2015 16:01:37 GMT
Server: Apache/2.4.7 (Ubuntu)
Content-Length: 623
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator at 
 administrator@91.103.6.23 to inform them of the time this error occurred,
 and the actions you performed just before this error.</p>
<p>More information about this error may be available
in the server error log.</p>
<hr>
<address>Apache/2.4.7 (Ubuntu) Server at adventorious.com Port 80</address>
</body></html>

我不明白為什么會這樣,因為它可以在本地計算機上完美運行,但是如果我嘗試從VPS運行它,則會拋出錯誤500。

我在網上搜索了所有內容,但似乎找不到解決方法。

非常感謝所有幫助。

加成;

這是錯誤;

[Sun Feb 15 16:17:53.470691 2015] [:error] [pid 1469] [client 178.167.254.175:4226] mod_wsgi (pid=1469): Target WSGI script '/var/www/FlaskApi/api.wsgi' cannot be loaded as Python module.
[Sun Feb 15 16:17:53.470790 2015] [:error] [pid 1469] [client 178.167.254.175:4226] mod_wsgi (pid=1469): Exception occurred processing WSGI script '/var/www/FlaskApi/api.wsgi'.
[Sun Feb 15 16:17:53.470817 2015] [:error] [pid 1469] [client 178.167.254.175:4226] Traceback (most recent call last):
[Sun Feb 15 16:17:53.470849 2015] [:error] [pid 1469] [client 178.167.254.175:4226]   File "/var/www/FlaskApi/api.wsgi", line 6, in <module>
[Sun Feb 15 16:17:53.470932 2015] [:error] [pid 1469] [client 178.167.254.175:4226]     from FlaskApi import app as application
[Sun Feb 15 16:17:53.470957 2015] [:error] [pid 1469] [client 178.167.254.175:4226] ImportError: No module named FlaskApi

我說; 從FlaskApi導入應用程序

但是wsgi和init文件位於同一位置,這是問題>>嗎?

看來您確實在嘗試從FlaskApi導入應用程序,但是您已經在其中。

您可以嘗試將腳本的第6行更改為:

from . import app as application

要么

import app as application

為了更快地進行測試(並避免一直重新啟動服務器),您還可以嘗試運行:

python /var/www/FlaskApi/api.wsgi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM