检查包含a-z或A-Z的数据

时间:2016-03-28 13:40:31

标签: python

我请求获取随机用户并将其添加到我的数据库进行测试。 不幸的是,其中一些数据不是英文的。

实施例

enter image description here

这导致了糟糕的数据,打破了我的桌面,我正在渲染。

enter image description here

我在想

检查api数据,看看它是否是英文字符。 如果是,请将其插入数据库,否则退出系统。

if firstname.isalpha():
    cur.execute(sql,args)
else:
    sys.exit()

但由于某种原因,它仍然插入,:(

关于这个问题的任何提示/建议对我来说意义重大。

我有

#!/usr/bin/python
import MySQLdb
import random
import requests
import time
import sys
import datetime

from random import randrange
from datetime import timedelta
from time import gmtime, strftime

def random_date(start, end):
    """
    This function will return a random datetime between two datetime
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

d1 = datetime.datetime.strptime('2016-03-27 11:16:32', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime(strftime('%Y-%m-%d %H:%M:%S', gmtime()), '%Y-%m-%d %H:%M:%S')
print strftime("%m/%d/%Y %I:%M %p", gmtime())


db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="*********",  # your password
                     db="db-local")       # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
    random.randint(0x00, 0x7f),
    random.randint(0x00, 0xff),
    random.randint(0x00, 0xff) ]

device_mac =  ':'.join(map(lambda x: "%02x" % x, mac))
device_mac = device_mac.replace(":","").upper()


cpe_mac = '000D6766F2F6'

url = "https://randomuser.me/api/"
data = requests.get(url).json()
firstname = data['results'][0]['user']['name']['first']
lastname = data['results'][0]['user']['name']['last']
email = data['results'][0]['user']['email']
gender = data['results'][0]['user']['gender']


age_range_options = ["<15", "15-25", "25-40","40+"]
age_range = random.choice(age_range_options)

ip = ".".join(map(str, (random.randint(0, 255)
    for _ in range(4))))

host_name = 'crontab'
os = 'iPhone OS 9.0'
visit_count = 1

rand_date = random_date(d1, d2);

created_at = time.strftime('%Y-%m-%d %H:%M:%S')
updated_at = time.strftime('%Y-%m-%d %H:%M:%S')

sql = ('''INSERT INTO visitors (device_mac,cpe_mac,firstname, lastname, email, gender, age_range,ip,host_name,os,visit_count,created_at, updated_at) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''')

args = (device_mac,cpe_mac, firstname, lastname, email, gender, age_range,ip, host_name,os,visit_count, created_at, updated_at)

if firstname.isalpha():
    cur.execute(sql,args)
else:
    sys.exit()

db.commit()
db.close()

1 个答案:

答案 0 :(得分:2)

عالي 之类的内容 alpha 数字...只是在另一个 alpha 下注中:

>>> a = u"عالي"
>>> a.isalpha()
True

实际上,如果你的整个堆栈正确处理unicode,它应该都可以工作。根据您上传的表格,唯一的问题是初始查找代码不能正确处理阿拉伯字符。

如果您想让您的应用以西方为中心而不是正确地将其国际化,您可以随时检查拉丁语字母表中的所有字母:

valid = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
def islatin(c): return c in valid

请注意,这也会禁止éô等字符...有关更全面的解决方案,请参阅this question