的數據是否爲請求獲取隨機用戶並將其添加到我的數據庫進行測試。 不幸的是,其中一些數據不是英文的。檢查包含a-z或A-Z
例子。
導致錯誤數據,並打破我的表,我正在呈現。
我想
檢查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()
將「prfzfndfj」視爲合適的英語嗎? – timgeb
「_That導致數據錯誤_」。怎麼會這樣?它對我來說看起來像一個完全合法的名字。考慮修復你的圖表,以便它們可以呈現任何類型的文本,而不是將輸入限制爲它當前可以呈現的文本類型。 – Kevin
任何包含英文字母的東西。我會很高興。 – ihue