Задать локальную переменную среды Bluemix VCAP_SERVICES, чтобы я мог разрабатывать ее локально?
Я пытаюсь установить мой Bluemix VCAP_SERVICES
переменная окружения локально, но я получаю эту ошибку в терминале:
NoSQL: команда не найдена
Действия по воспроизведению
- Войдите в Bluemix.net
- Разверните приложение Hello World!
- Привязать службу Bluemix Cloudant к приложению
- Скопируйте
VCAP_SERVICES
Переменные среды из переменных среды выполнения / среды в приложении для Python - В локальном редакторе удалите все разрывы строк на терминале Mac
vi ~/.bash_profile
- Войдите в режим вставки с помощью
i
вставить в
VCAPSERVICES
Моя выглядит так:VCAP_SERVICES="{"VCAP_SERVICES":{"cloudantNoSQLDB": [{"credentials": {"host": "fakehostc-bluemix.cloudant.com","password":"fakepassword4da6de3a12a83362b26a","port": 443,"url": "https://fakeURLc-bluemix:fakeab96175c-bluemix.cloudant.com","username": "fakeusername-b749-399cfbd1175c-bluemix"},"label":"cloudantNoSQLDB","name":"Cloudant NoSQL DB-p2","plan":"Lite","provider":null,"syslog_drain_url":null,"tags":["data_management","ibm_created","ibm_dedicated_public"]}]}}" export VCAP_SERVICES
Сохраните файл и выйдите
vi
с:wq!
- Исходный модифицированный файл с
. ~/.bash_profile
установить окно терминала с новой переменной среды VCAP
Что я делаю неправильно, копируя и устанавливая локальную переменную среды Bluemix VCAP_Services?
Если я копирую все это, я получаю ошибки, что строка слишком длинная. Как я могу легко скопировать и вставить всю среду выполнения Bluemix Python VCAP_SERVICES
Переменная в мой локальный Mac .bash_profile
настройки среды без ручного массирования JSON и всех этих разрывов строк и т. д.?
Я не хочу использовать локальный файл для их хранения, поскольку он не очень безопасен, так как я перехожу с dev, test, staging и production.
3 ответа
Я разобрался с ответом, используя одинарные кавычки в начале и конце VCAP_SERVICES
VCAP_SERVICES = '{"cloudantNoSQLDB": [{"credentials": {"host": "fakehostc-bluemix.cloudant.com", "password": "fakepassword4da6de3a12a83362b26a", "port": 443, "url": " https://fakeURLc-bluemix:fakeab96175c-bluemix.cloudant.com"," username ":" fakeusername-b749-399cfbd1175c-bluemix "}," label ":" cloudantNoSQLDB "," name ":" Cloudant NoSQL DB-p2 ", "план":"Lite","поставщик": нулевой,"syslog_drain_url": нулевой, "метки":["data_management","ibm_created","ibm_dedicated_public"]}]}"
Вот соответствующий код для извлечения переменных среды VCAP Services и выполнения основных операций в Cloudant:
# 1. Parse VCAP_SERVICES Variable and connect to DB
vcap = json.loads(os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB']
serviceUsername = vcap[0]['credentials']['username']
servicePassword = vcap[0]['credentials']['password']
serviceURL = vcap[0]['credentials']['url']
# Create Cloudant DB connection
# This is the name of the database we are working with.
databaseName = "databasedemo"
# This is a simple collection of data,
# to store within the database.
sampleData = [
[1, "one", "boiling", 100],
[2, "two", "hot", 40],
[3, "three", "warm", 20],
[4, "four", "cold", 10],
[5, "five", "freezing", 0]
]
# Use the Cloudant library to create a Cloudant client.
client = Cloudant(serviceUsername, servicePassword, url=serviceURL)
# Connect to the server
client.connect()
# 2. Creating a database within the service instance.
# Create an instance of the database.
myDatabaseDemo = client.create_database(databaseName)
# Check that the database now exists.
if myDatabaseDemo.exists():
print "'{0}' successfully created.\n".format(databaseName)
# 3. Storing a small collection of data as documents within the database.
# Create documents using the sample data.
# Go through each row in the array
for document in sampleData:
# Retrieve the fields in each row.
number = document[0]
name = document[1]
description = document[2]
temperature = document[3]
# Create a JSON document that represents
# all the data in the row.
jsonDocument = {
"numberField": number,
"nameField": name,
"descriptionField": description,
"temperatureField": temperature
}
# Create a document using the Database API.
newDocument = myDatabaseDemo.create_document(jsonDocument)
# Check that the document exists in the database.
if newDocument.exists():
print "Document '{0}' successfully created.".format(number)
# 4. Retrieving a complete list of the documents.
# Simple and minimal retrieval of the first
# document in the database.
result_collection = Result(myDatabaseDemo.all_docs)
print "Retrieved minimal document:\n{0}\n".format(result_collection[0])
# Simple and full retrieval of the first
# document in the database.
result_collection = Result(myDatabaseDemo.all_docs, include_docs=True)
print "Retrieved full document:\n{0}\n".format(result_collection[0])
# Use a Cloudant API endpoint to retrieve
# all the documents in the database,
# including their content.
# Define the end point and parameters
end_point = '{0}/{1}'.format(serviceURL, databaseName + "/_all_docs")
params = {'include_docs': 'true'}
# Issue the request
response = client.r_session.get(end_point, params=params)
# Display the response content
print "{0}\n".format(response.json())
# 5. Deleting the database.
# Delete the test database.
try :
client.delete_database(databaseName)
except CloudantException:
print "There was a problem deleting '{0}'.\n".format(databaseName)
else:
print "'{0}' successfully deleted.\n".format(databaseName)
# 6. Closing the connection to the service instance.
# Disconnect from the server
client.disconnect()
Это анти-шаблон для локального создания переменной env VCAP_SERVICES. Я предлагаю просто использовать информацию о соединении при запуске локально.
Опция 1
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
cloudant_url = services['cloudantNoSQLDB'][0]['credentials']['url']
else:
cloudant_url = "https://fakeURLc-bluemix:fakeab96175c-bluemix.cloudant.com"
Вариант 2
Если вы не хотите жестко вводить учетные данные в свой код, то вы можете создать .env
файл:
export LOCAL_CLOUDANT_URL=https://fakeURLc-bluemix:fakeab96175c-bluemix.cloudant.com
и в вашем коде Python:
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
cloudant_url = services['cloudantNoSQLDB'][0]['credentials']['url']
else:
cloudant_url = os.environ['LOCAL_CLOUDANT_URL']
а потом source .env
прежде чем запустить приложение.
Обязательно добавлю .env
в .gitignore
а также .cfignore
Существует плагин cf CLI, который получит VCAP_SERVICES из вашего приложения и поможет вам установить его локально. Я использовал его на своем Mac и не должен был корректировать кавычки вообще.
Оформить заказ https://github.com/jthomas/copyenv