Python小技巧暨問題集


緣由

工作上有需要用到的一些python技巧記錄

串列的append()和extend()

append()

cars1 = ['toyota','nissan','honda']
cars2 = ['ford','audi']
print(cars1)
print(cars2)
cars1.append(cars2)
print(cars1)
print(cars2)

輸出結果,直接以串列型態附加到串列內
['toyota', 'nissan', 'honda']
['ford', 'audi']
['toyota', 'nissan', 'honda', ['ford', 'audi']]
['ford', 'audi']

extend()

cars1 = ['toyota','nissan','honda']
cars2 = ['ford','audi']
print(cars1)
print(cars2)
cars1.extend(cars2)
print(cars1)
print(cars2)

輸出結果,將串列元素取出後再附加於串列內
['toyota', 'nissan', 'honda']
['ford', 'audi']
['toyota', 'nissan', 'honda', 'ford', 'audi']
['ford', 'audi']

與MySQL互動

安裝mysql python驅動

$ pip3 install mysql-connector-python

實作範例

def get_gw_snid(fbee_user:str, fbee_password:str) -> list:
    """ 到資料庫查詢帳密對應的snid """
    dbconfig = {
        'host' : '127.0.0.1',
        'port' : 3306,
        'user' : 'xxx',
        'password' : 'xxx',
        'database' : 'xxx',
        'charset' : 'utf8'
    }

    try:
        conn = mysql.connector.connect(**dbconfig)

        if conn.is_connected():
            report_server_logger.info("資料庫連線已建立")
            cursor = conn.cursor()
            _SQL = """select gw_uid from customer_gateway
                    where api_com_id=%s and account=%s and password=%s"""
            cursor.execute(_SQL,('2',fbee_user,fbee_password))
            return cursor.fetchall()

    except Error as e:
        report_server_logger.error("資料庫連接失敗 %s",e)
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()
            report_server_logger.info("資料庫連線關閉")

與MongoDB互動

安裝mongodb python驅動

剛開始一直無法安裝

$ pip3 install pymongo
Traceback (most recent call last):
  File "/home/firstuser/.local/bin/pip3", line 7, in <module>
    from pip._internal.cli.main import main
  File "/home/firstuser/.local/lib/python3.5/site-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

$ python3 -m pip3 install pymongo
/usr/bin/python3: No module named pip3

查了一下資訊,pip3在python3.5不再支援,必須3.6以上,參考了 在Ubuntu 18.04上遇到No module named ‘pip._internal’ | by Mike | Medium 重新安裝pip3,然後不要再去更新pip3

$ curl https://bootstrap.pypa.io/pip/3.5/get-pip.py -o get-pip.py
$ python3 get-pip.py --force-reinstall

然後再去安裝pymongo

$ pip3 install pymongo

實作範例

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["xxx"]
mycol = mydb["xxx"]

myquery = { "gateway_sn": "xxxxxx","addr":"xxxx" }

for x in mycol.find(myquery,{"_id":0,"deviceid":1,"zonetype":1}):
    if x['deviceid'] == '0204':
        devid_zonetype = x['deviceid']+x['zonetype']
        print(device_zone_name_mapping[devid_zonetype])
    else:
        print(device_zone_name_mapping[x['deviceid']])
#Python






你可能感興趣的文章

[W3-r24-D16]_the-Goal

[W3-r24-D16]_the-Goal

與 CSS Grid 的第一次接觸

與 CSS Grid 的第一次接觸

Create a role when first starting up the PostgreSQL DB

Create a role when first starting up the PostgreSQL DB






留言討論