TypeError Python CGI脚本

时间:2014-11-16 18:16:05

标签: python cgi typeerror

我有一个网站,当点击一个按钮时,通过AJAX运行一个简单的python CGI脚本。问题是我得到TypeError,但我不知道问题是什么。

Python代码:

#!C:\Python27\python.exe
#Steam64 ID - 76561198041707719
import urllib
import cgi
import itertools
import urllib2
import time
from datetime import datetime
from bs4 import BeautifulSoup
from flask import Flask, jsonify, render_template, redirect
import requests
import json
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
import sys

API_KEY = 'XXX'
API_BASEURL = 'http://api.steampowered.com/'
API_GET_FRIENDS = API_BASEURL + 'ISteamUser/GetFriendList/v0001/?key='+API_KEY+'&steamid='
API_GET_SUMMARIES = API_BASEURL + 'ISteamUser/GetPlayerSummaries/v0002/?key='+API_KEY+'&steamids='
PROFILE_URL = 'http://steamcommunity.com/profiles/'
steamIDs = []
myFriends = []
form = cgi.FieldStorage()
steeam = form.getfirst('steamid')

class steamUser:
    def __init__(self, name, steamid, picture, profileurl, profilestate, isPhisher):
        self.name = name
        self.steamid = steamid
        self.isPhisher = isPhisher
        self.profileurl = profileurl
        if profilestate == '0':
            self.profilestate = '<span style=\"color:#616161\";>(Offline)</span>'
            self.picture = '<img class = \"offline\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        elif profilestate == '1':
            self.profilestate = '<span style=\"color:#006EFF\";>(Online)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        elif profilestate == '2':
            self.profilestate = '<span style=\"color:#006EFF\";>(Busy)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        elif profilestate == '3':
            self.profilestate = '<span style=\"color:#006EFF\";>(Away)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        elif profilestate == '4':
            self.profilestate = '<span style=\"color:#006EFF\";>(Snooze)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        elif profilestate == '5':
            self.profilestate = '<span style=\"color:#006EFF\";>(Looking to Trade)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'
        else:
            self.profilestate = '<span style=\"color:#006EFF\";>(Looking to Play)</span>'
            self.picture = '<img class = \"border\" src=\"" + picture + "\" title = \"\" alt = \"\">'

    def setPhisherStatus(self, phisher):
        self.isPhisher = phisher

    def toString():
        return '<div id = \"phisher-profile\"><h3>' + self.picture + '</br> </br>' + self.name + '</br>' + self.profilestate + '</br>' + 'Steam ID: ' + self.steamid + '</br>' + '<a href=' + self.profileurl + '>Steam Profile</a></br> </br>' + '<\h3><\div>'

def getFriendList(steamid):
    try:
        r = requests.get(API_GET_FRIENDS+steamid, timeout=3)
        data = r.json()
        for friend in data['friendslist']['friends']:
            steamIDs.append(friend['steamid'])
        return isPhisher(steamIDs)
    except requests.exceptions.ConnectionError as e:
        return "Connection Error:", str(e.message)

def isPhisher(ids):
    phisherusers = ''
    for l in chunksiter(ids, 50):
        sids = ','.join(map(str, l))
        try:
            r = requests.get(API_GET_SUMMARIES+sids, timeout=3)
            data = r.json();
            for i in range(len(data['response']['players'])):
                steamFriend = data['response']['players'][i]
                n = steamUser(steamFriend['personaname'], steamFriend['steamid'], steamFriend['avatarfull'], steamFriend['profileurl'], steamFriend['personastate'], False)
                if steamFriend['communityvisibilitystate'] and not steamFriend['personastate']:
                    url =  PROFILE_URL+steamFriend['steamid']+'?xml=1'
                    dat = requests.get(url, timeout=3)
                    if 'profilestate' not in steamFriend:
                        n.setPhisherStatus(True);
                        phisherusers = phisherusers + n.toString()
                    if parseString(dat.text.encode('utf8')).getElementsByTagName('privacyState'):
                        privacy = str(parseString(dat.text.encode('utf-8')).getElementsByTagName('privacyState')[0].firstChild.wholeText)
                        if (privacy == 'private'):
                            n.setPhisherStatus(True)
                            phisherusers = phisherusers + n.toString()
                elif 'profilestate' not in steamFriend:
                    n.setPhisherStatus(True);
                    phisherusers = phisherusers + n.toString()
                else:
                    steamprofile = BeautifulSoup(urllib.urlopen(PROFILE_URL+steamFriend['steamid']).read())
                    for row in steamprofile('div', {'class': 'commentthread_comment  '}):
                        comment = row.find_all('div', 'commentthread_comment_text')[0].get_text().lower()
                        if ('phisher' in comment) or ('scammer' in comment):
                            n.setPhisherStatus(True)
                            phisherusers = phisherusers + n.toString()
                myFriends.append(n);
        except requests.exceptions.ConnectionError as e:
            return "Connection Error:", str(e.message)
        except:
            return "Unexpected error:", sys.exc_info()[0]
    if phisherusers == '':
        return 'User has no phishers!'
    return phisherusers

def chunksiter(l, chunks):
    i,j,n = 0,0,0
    rl = []
    while n < len(l)/chunks:        
        rl.append(l[i:j+chunks])        
        i+=chunks
        j+=j+chunks        
        n+=1
    return iter(rl)

print "Content-type: text/html\n"
print "<div id=\"phisher-users\">"
print getFriendList('76561198041707719')
print "</div>"

当我执行脚本时。它运行这一行:

except:
    return "Unexpected error:", sys.exc_info()[0]

这是输出:

('Unexpected error:', 
<type 'exceptions.typeerror'="">)
</type>

我感谢任何帮助。

0 个答案:

没有答案