Невозможно использовать прокси для подключения к Documentdb с помощью Python - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь подключиться к моему documentDB Azure через прокси-сервер, но у меня ошибка ниже:

поднять ConnectionError (e, request = request) запросы. Исключение. com ', port = xxx): максимальное количество повторных попыток превышено с помощью url: / (вызвано NewConnectionError (': не удалось установить новое соединение: [Errno 11004] getaddrinfo fail '))

код ниже:

#coding:utf-8
from pydocumentdb import document_client
import azure.cosmos.documents as documents
uri = 'xxxxxxx.azure.com:443/'
key = 'xxxxxxxxxx'
connection_policy = documents.ConnectionPolicy()
connection_policy.ProxyConfiguration = documents.ProxyConfiguration()
connection_policy.ProxyConfiguration.Host = 'xxx.xx.xx.xxx'
connection_policy.ProxyConfiguration.Port = xxxx #I also have trid with = 'xxxx'
client = document_client.DocumentClient(uri, {'masterKey': key}, connection_policy)
db_id = 'Store'
db_query = "select * from r where r.id = '{0}'".format(db_id)
db = list(client.QueryDatabases(db_query))[0]
db_link = db['_self']

coll_id = 'collection'
coll_query = "select * from r where r.id = '{0}'".format(coll_id)
coll = list(client.QueryCollections(db_link, coll_query))[0]
coll_link = coll['_self']


query = { 'query': 'select c.date as date from c' }
result_iterable = client.QueryDocuments(coll_link, query)
for item in iter(result_iterable):
   date= str(item["date"])

1 Ответ

0 голосов
/ 01 ноября 2019

Я проверил ваш код, и он работает для меня.

from pydocumentdb import document_client
import azure.cosmos.documents as documents

uri = 'https://***.documents.azure.com:443/'
key = '***'
connection_policy = documents.ConnectionPolicy()
connection_policy.ProxyConfiguration = documents.ProxyConfiguration()
connection_policy.ProxyConfiguration.Host = '***'
connection_policy.ProxyConfiguration.Port = 8080
client = document_client.DocumentClient(uri, {'masterKey': key}, connection_policy)
db_id = 'db'
db_query = "select * from r where r.id = '{0}'".format(db_id)
db = list(client.QueryDatabases(db_query))[0]
db_link = db['_self']

coll_id = 'coll'
coll_query = "select * from r where r.id = '{0}'".format(coll_id)
coll = list(client.QueryCollections(db_link, coll_query))[0]
coll_link = coll['_self']

query = {'query': 'select c.title as title from c'}
options = {'enableCrossPartitionQuery': 'true'}
result_iterable = client.QueryDocuments(coll_link, query, options)
for item in iter(result_iterable):
    title = str(item["title"])
    print(title)
    break

Вывод:

enter image description here

Мой прокси-серверпростой сервер nodejs, который работает на другой стороне и прослушивает 8080 порт:

var http = require('http');
// proxy url host
var HOST = 'localhost';
// server port
var PORT = 8080;

var log = function () {
  var now = new Date().toISOString();
  arguments[0] = '[' + now + '] ' + arguments[0];
  console.log.apply(console, arguments);
};

var getHeader = function (req) {
  var ret = {};
  for (var i in req.headers) {
    if (!/host|connection/i.test(i)) {
      ret[i] = req.headers[i];
    }
  }
  return ret;
};

var getPath = function (req) {
  var url = req.url;
  if (url.substr(0, 7).toLowerCase() === 'http://') {
    var i = url.indexOf('/', 7);
    if (i !== -1) {
      url = url.substr(i);
    }
  }
  return url;
};

var counter = 0;
var onProxy = function (req, res) {
  counter++;
  var num = counter;
  var opt = {
    host:     HOST,
    path:     getPath(req),
    method:   req.method,
    headers:  getHeader(req)
  };
  log('#%d\t%s http://%s%s', num, req.method, opt.host, opt.path);
  var req2 = http.request(opt, function (res2) {
    res.writeHead(res2.statusCode, res2.headers);
    res2.pipe(res);
    res2.on('end', function () {
      log('#%d\tEND', num);
    });
  });
  if (/POST|PUT/i.test(req.method)) {
    req.pipe(req2);
  } else {
    req2.end();
  }
  req2.on('error', function (err) {
    log('#%d\tERROR: %s', num, err.stack);
    res.end(err.stack);
  });
};

var server = http.createServer(onProxy);
server.listen(PORT);
console.log('start listening port:' + PORT);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...