Как принять ввод пользователя и позволить ему загрузить / отправить файл .json в образ Docker
Итак, я довольно новичок в Docker, но мне уже очень нравятся его функциональные возможности и менталитет контейнеров/блоков.
Длинная история, в последнее время я продавал некоторые скрипты, но постоянно сталкивался с одной и той же проблемой. Мои клиенты обычно работали под Windows, и мне приходилось тратить много времени на их настройку, ломаные пакеты в Windows, надоедливые сессии TeamViewer и т.д.
Теперь в дело вступает такой прекрасный инструмент, как Docker, который позволяет мне поставлять готовые образы. Просто фантастика!
Учитывая мой статус новичка в Docker, у меня возникают некоторые проблемы с выполнением определенных действий. В настоящее время я читаю книгу "Docker в действии" и мне она очень нравится, но что-то похожее на мою проблему там (пока) не рассматривалось.
Теперь у меня есть следующий код (это не все, но часть, с которой я борюсь):
def broadcast_transaction(sender, private_key, amount, contract):
# Get the nonce. Prevents one from sending the transaction twice
nonce = web3.eth.getTransactionCount(sender)
to_address = web3.toChecksumAddress(contract)
# Build a transaction in a dictionary
tx = {
'nonce': nonce,
'to': to_address,
'value': web3.toWei(amount, 'gwei'),
'gas': 300000,
'gasPrice': web3.toWei('5', 'gwei'),
'chainId': 0x38
}
# sign the transaction
signed_tx = web3.eth.account.sign_transaction(tx, private_key)
# send transaction
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
# get transaction hash
tx_id = web3.toHex(tx_hash)
print(f"Transaction: \n\n"
f"From: {sender}\n"
f"To: {to_address}\n"
f"Status: successful\n"
f"\n"
f"TxID is: {tx_id}")
print("Please input the EXACT address of the receiver contract or address. \nPress ENTER after having pasted the "
"contract / account address or type Q to quit.\n")
contract_address = str(input())
print("Please input the EXACT filename of the json file, including .json. \nPress ENTER after having pasted the "
"filename or type Q to quit.\n")
json_filename = str(input())
if json_filename.lower() == "q":
sys.exit()
delay = int(input("Please input the delay you want to set in WHOLE minutes.\nGOOD: 1 3 9 16 20\nWRONG: 1.5, 16.89, "
"218.2315\nPress ENTER after having typed in the input\n"))
delay = delay * 60
# Opening JSON file
f = open(json_filename)
# returns JSON object as
# a dictionary
data = json.load(f)
Как вы видите, я принимаю несколько входных данных. Человек, использующий этот скрипт, должен:
- Provide his pubkey
- Provide his private key
- Amount is hardcoded
- Receiver pubkey
- As json from which to load addresses.
Теперь подытожим мои вопросы:
Can I store the pub- and private-key inside a .env? Does .env work with Docker / is it advisable. I would have to build for every change for the sender.
How can I make it so that the user can still provide the address and filename without having to hardcode it?
How do I get a .json that changes for every run of the script into the image? Since I am shipping the image without the .json (.json is provided by client).
Теперь у меня есть одна идея, которая заключается в создании веб-сервера Django, который принимает входные данные через веб-сайт, что также было бы классным личным проектом, но мне интересно, что более опытные и профессиональные пользователи Docker будут делать в этой ситуации.