I created connection like that
https://docs.openstack.org/openstacksdk/latest/user/guides/connect.html
def create_connection(project_id=None) -> Optional[Connection]:
"""
Create connection to Client's Project in Openstack
:param project_id:
:return: Connection
"""
os_project_id = project_id or settings.OPENSTACK.get("PROJECT_ID")
return openstack.connect(
auth_url=settings.OPENSTACK.get("AUTH_URL"),
project_id=os_project_id,
username=settings.OPENSTACK.get("USERNAME"),
password=settings.OPENSTACK.get("PASSWORD"),
user_domain_name=settings.OPENSTACK.get("USER_DOMAIN_NAME"),
project_domain_name=settings.OPENSTACK.get("PROJECT_DOMAIN_NAME"),
app_name="default",
app_version="1.0",
)
# call function create connection
conn = create_connection(project_id)
# get project
project = conn.identity.get_project(project_id)
# conn2 with project id of client
conn2 = conn.connect_as_project(project)
I succeeded get project and created conn2 in first time, but in the second, i couldn't get connection and created conn2.
It was raise exception
HttpException: No Project found for 40e090c7ee32405dae3d2814cce73094: Client Error for url: https://{BASE_URL}:5000/v3/projects/40e090c7ee32405dae3d2814cce73094, You are not authorized to perform the requested action: identity:get_project.
I thought it cached session and used conn like conn2 created
Related
While I was writing the Async test code for FASTAPI there is a problem that cannot be solved. this code is for test db. I'm using postgres and in order to user db as a test, I created is_testing function. It drop and create test db.
if is_testing:
db_url = self._engine.url
if db_url.host != "localhost":
raise Exception("db host must be 'localhost' in test environment")
except_schema_db_url = f"{db_url.drivername}://{db_url.username}#{db_url.host}"
schema_name = db_url.database # test
temp_engine = create_engine(except_schema_db_url, echo=echo, pool_recycle=pool_recycle, pool_pre_ping=True)
conn = temp_engine.connect()
try:
conn = conn.execution_options(autocommit=False)
conn.execute("ROLLBACK")
conn.execute(f"DROP DATABASE {schema_name}")
except ProgrammingError:
print(f"could not drop the database, probably does not exist.")
conn.execute("ROLLBACK")
except OperationalError:
print("could not drop database because it's being accessed by other users(psql prompt open?)")
conn.execute("ROLLBACK")
print(f"test db dropped! about to create {schema_name}")
conn.execute(f"CREATE DATABASE {schema_name}")
try:
conn.execute(f"create user test with encrypted password test")
except:
print("User already exist")
temp_engine.dispose()
this is conftest.py
#pytest.fixture(scope="session")
def app():
os.environ["API_ENV"] = "test"
return create_app()
#pytest.fixture(scope="session")
def client(app):
Base.metadata.create_all(db.engine)
# Create tables
client = AsyncClient(app=app, base_url="http://test")
return client
#pytest.fixture(scope="function", autouse=True)
def session():
sess = next(db.session())
yield sess
clear_all_table_data(
session=sess,
metadata=Base.metadata,
except_tables=[]
)
sess.rollback()
def clear_all_table_data(session: Session, metadata, except_tables: List[str] = None):
session.execute("SET session_replication_role = 'replica';")
for table in metadata.sorted_tables:
if table.name not in except_tables:
session.execute(table.delete())
session.execute("SET session_replication_role = 'origin';")
session.commit()
I got error sqlalchemy.exc.OperationalError: (psycopg2.errors.ObjectInUse) database "test" is being accessed by other users DETAIL: There is 1 other session using the database. in elb check test.
and I got error TypeError: 'AsyncClient' object is not callable in another api test.
I modified client function in conftest.py
#pytest.fixture(scope="session")
def client(app):
Base.metadata.create_all(db.engine)
return AsyncClient(app=app, base_url="http://test")
I passed one test, but I received the following error from the second test.
ClientState.OPENED: "Cannot open a client instance more than once.",
ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",
how can I fix it?
thank you for reading long question!
I have the following thrift server (socket), listening for connections on a specific host/port.
final TProtocolFactory factory = new TBinaryProtocol.Factory();
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(serverPort);
final SignatureService.Processor theProcessor = new SignatureService.Processor(new SignatureServiceFacade());
TServer server = new THsHaServer(new THsHaServer.Args(serverTransport).processor(theProcessor).
protocolFactory(factory).
minWorkerThreads(minThreads).
maxWorkerThreads(maxThreads));
And following client connection:
clientTransport = new TFramedTransport(new TSocket(signatureHost, signaturePort));
final TProtocol theProtocol = new TBinaryProtocol(clientTransport);
client = new SignatureService.Client(theProtocol);
clientTransport.open();
//call the business specific method
client.doStuff(param1, param2, param3);
As we can see in the code above I need to provide the host and port in order to open a connection with the server.
But I want to use a service discovery with load balance support, because I'll have multiple instances of my service running.
Anybody has an example of this using nginx? All the examples is using regular http rest based applications.
Tks in advance.
I set up SendGrid account and got key and pw.
My VisualBasic 2015 console app runs DeliverAsync without error, but email doesn't get to Internet receipients (my Hotmail account).
Also, the task.wait() throws exception "Bad username / password", which is posted at the end
Wireshark on Azure shows no SMTP, but I don't know if SendGrid uses SMTP.
Here is the app:
' Create the email object first, then add the properties.
Dim myMessage As SendGridMessage
myMessage = New SendGridMessage()
' Add the message properties.
myMessage.From = New MailAddress("<my email addr>")
' Add multiple addresses to the To field.
myMessage.AddTo("<destination email addr 1>")
myMessage.AddTo("<destination email addr 2>")
myMessage.AddTo("<destination email addr 3>")
myMessage.Subject = "Testing the SendGrid Library 2"
'Add the HTML and Text bodies
myMessage.Html = "<p>Hello World!</p>"
myMessage.Text = "Hello World plain text!"
Dim credentials As NetworkCredential
credentials = New NetworkCredential("apikey", "<my api pw>")
transportWeb = New Web(credentials)
Dim task = transportWeb.DeliverAsync(myMessage)
Try
task.wait()
Catch ex As AggregateException
Stop '<<<<<<<<< I GET: "Bad username / password"
Catch
End Try
EXCEPTION DETAILS:
"Bad username / password"
DeliverAsync returns a Task, so you need to await the task.
Await transportWeb.DeliverAsync(myMessage)
Of course, to use the await keyword your method needs to be marked as async. If you don't want to do that, then you can manually wait on the task.
Dim task = transportWeb.DeliverAsync(myMessage)
task.Wait()
You should familiarize yourself with the Task-based Asynchronous Pattern (TAP). Often when a function name ends in -Async then it uses TAP.
I got it working by creating new VB web app instead of win app.
VB > create new proj > web app > MVC and then props > references > NU.. Mgr > search SendGrid > Install, and that's it.
CRM Portal is setup on "crmstaging" machine, on port 5555.
Following is the path of CRM Service:
http://crmstaging:5555/MSCrmServices/2007/CrmService.asmx
I am creating an ASP.NET Website on my dev machine "crmdev", and have added reference of the above service.
Now, I am trying to use various methods of this service to perform operations on my CRM entities, for that, I have written following code in button click of the page:
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "MyCompany";
CrmService service = new CrmService();
service.CrmAuthenticationTokenValue = token;
service.Credentials = new System.Net.NetworkCredential("username","password","domainname");
//service.Credentials = System.Net.CredentialCache.DefaultCredentials;
string fetch1 = #"<fetch mapping=""logical"">
<entity name=""account"">
<all-attributes/>
</entity>
</fetch>";
String result1 = service.Fetch(fetch1);
txtBox1.Text = result1;
In above code, I have passed credentials of the user having access on CRM Staging machine.
While trying to execute this code, I get an error saying "401 Unauthorized".
How to resolve this issue?
I want to count the online user,when each client login the system,it's connecting to the server and increase a variable stored in a remote shared object.
But when client connecting server,problems arises:Error #2126: NetConnection object must be connected
My web layout:
Website --- apps --- userLogin
Code snippets:
rtmpnc = new NetConnection();
rtmpnc.objectEncoding = ObjectEncoding.AMF0;
var uri:String = ServerConfig.getChannel("my-rtmp").endpoint + "/userLogin";
rtmpnc.connect("http://202.206.249.193:2367/userLogin");
rtmpnc.addEventListener(NetStatusEvent.NET_STATUS,onNetStatusHandler);
The onNetStatusHander is defined as :
switch(event.info.code)
{
case "NetConnection.Connect.Success":onConnSuccess();break;
case "NetConnection.Connect.Failed":onConnError();break;
}
Could anyoue help me out?Much thanks!
Best,Shuo
Move the eventListener to the line above the connect() (just in case). Also add a SecurityErrorEvent.SECURITY_ERROR eventListener before your connect. I'm going to guess we're looking at a security sandbox problem.