silwyne commented on issue #20546:
URL: https://github.com/apache/superset/issues/20546#issuecomment-3315555312

   Hi everyone !
   I made it!
   for creating a database in superset using HTTP api you must use this python 
code:
   ```
   import sys
   import requests
   import json
   import logging as Logger
   
   TIMEOUT = 3
   class Utils():
       @staticmethod
       def log_http_response(response: requests.Response):
           Logger.info(f"API result: \n{json.dumps(response.json(), indent=2)}")
   
       @staticmethod
       def answer_to_bool(answer: str) -> bool:
           answer = answer.upper()
           if answer == "YES" or answer == "Y":
               return True
           elif answer == "NO" or answer == "N":
               return False
           Logger.error(f"{answer} as answer is not valid. valid responses: 
(YES/NO)(yes/no)(Y/N)(y/n)")
           sys.exit(1)
       
       @staticmethod
       def abort(message: str):
           Logger.error(message)
           Logger.error("Aborting the operation.")
           sys.exit(1)
   
   class SupersetHTTPService:
       @staticmethod
       def get_csrf_authenticated_session(
               superset_host: str,
               user: str,
               password: str,
               access_token: str = None,
           ) -> requests.Session:
           
           if not access_token:
               access_token = SupersetHTTPService._get_access_token(
                   superset_host=superset_host,
                   user=user,
                   password=password,
               )
           
           session = requests.Session()
           session.headers.update({'Referer': superset_host})
           session.headers.update({'Authorization': f'Bearer {access_token}'})
           
           csrf_token = SupersetHTTPService._get_csrf_token(
               session=session,
               superset_host=superset_host,
           )
           session.headers.update({
                  'X-CSRFToken': csrf_token
               })
           return session
   
       @staticmethod
       def _get_csrf_token(
               session: requests.Session,
               superset_host: str,
           ) ->str:
           try:
               res = session.get(superset_host + "/api/v1/security/csrf_token/")
               res.raise_for_status()
               csrf_token = res.json()['result']
               return csrf_token
           except Exception as e:
               Utils.abort(f"Error while getting csrf token: {e}")
   
   
       @staticmethod
       def create_database(
           superset_host: str,
           user: str,
           password: str,
           database_name: str,
           engine: str,
           sqlalchemy_uri: str,
           other_parameters: str,
           access_token: str = None,
       ):
           if not access_token:
               access_token = SupersetHTTPService._get_access_token(
                   superset_host=superset_host,
                   user=user,
                   password=password,
               )
           
           session = SupersetHTTPService.get_csrf_authenticated_session(
               superset_host=superset_host,
               user=user,
               password=password,
               access_token=access_token,
           )
   
           json_data = {
               "database_name": database_name,
               "engine": engine,
               "sqlalchemy_uri": sqlalchemy_uri,
           }
           other_parameters = json.loads(other_parameters)
           for key, value in other_parameters.items():
               json_data[key] = value
   
           print(f"json_data: \n{json_data}")
   
           response = session.post(url=f"{superset_host}/api/v1/database", 
json=json_data)
           try:
               response.raise_for_status()
               return response
           except Exception as e:
               Utils.abort(f"Error while creating database {e}")
   
   
   def create_database(
           superset_host: str = None,
           user: str = None,
           password: str = None,
           database_name: str = None,
           engine: str = None,
           sqlalchemy_uri: str = None,
           other_parameters: str = None,
       ):
       response = SupersetHTTPService.create_database(
           superset_host=superset_host,
           user=user,
           password=password,
           database_name=database_name,
           engine=engine,
           sqlalchemy_uri=sqlalchemy_uri,
           other_parameters=other_parameters,
       )
       return response
   
   
   response = create_database(
       superset_host="http://localhost:8080";,
       user="admin",
       password="admin_pass_1234",
       database_name="Some_DB",
       engine="Clickhouse",
       
sqlalchemy_uri="clickhousedb+connect://admin:[email protected]:8124/Some_DB",
       other_parameters="",
   )
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to