codonPython package¶
Submodules¶
codonPython.age_bands module¶
-
codonPython.age_bands.
age_band_10_years
(age: int) → str¶ Place age into appropriate 10 year band
This function takes the age supplied as an argument and returns a string representing the relevant 10 year banding.
- Parameters
age (int) – Age of the person
- Returns
out – The 10 year age band
- Return type
str
Examples
>>> age_band_10_years(3) '0-9' >>> age_band_10_years(None) 'Age not known' >>> age_band_10_years(95) '90 and over'
-
codonPython.age_bands.
age_band_5_years
(age: int) → str¶ Place age into appropriate 5 year band
This function takes the age supplied as an argument and returns a string representing the relevant 5 year banding.
- Parameters
age (int) – Age of the person
- Returns
out – The 5 year age band
- Return type
str
Examples
>>> age_band_5_years(3) '0-4' >>> age_band_5_years(None) 'Age not known' >>> age_band_5_years(95) '90 and over'
codonPython.check_consistent_measures module¶
codonPython.check_consistent_submissions module¶
codonPython.check_nat_val module¶
codonPython.check_null module¶
codonPython.dateValidator module¶
codonPython.file_utils module¶
-
codonPython.file_utils.
compare
(x, y, names=['x', 'y'], dups=False, same=False, comment=False)¶ This function returns a dictionary with:
Same values between data frames x and y
Values in x, not in y
Values in y, not in x
(optional): (4) Duplicates of x (5) Duplicates of y (6) Boolean of whether x and y are the same
- Parameters
x (pandas.DataFrame) – DataFrame #1
y (pandas.DataFrame) – DataFrame #2
names (list) – a list of user preferred file names e.g. [‘File1’, ‘File2’] default = [‘x’,’y’]
dups (bool) – True to include duplicates check for each file default = False
same (bool) – True to activate. Outputs True if DataFrames are the same default = False
comment (bool) – True to activate. Prints out statistics of the compariosn results e.g. number of same valeus, number of duplicates, number of outliers and whether the DataFrames are the same default = False
- Returns
out
- Return type
dict
Examples
‘>>> c = compare(df1, df2, names = [‘df1’,’df2’], dups = True, same = True, comment =True)’
There are 133891 same values There are 16531 outliers in df1 There are 20937 outliers in df2 There are 48704 duplicates in df1 There are 0 duplicates in df2 The DataFrames are not the same
‘>>> c = compare(df2, df2, names = [‘df2’,’df2’], dups = True, same = True, comment =True)’
There are 154444 same values There are 0 outliers in df2 There are 0 outliers in df2 There are 0 duplicates in df2 There are 0 duplicates in df2 The DataFrames are the same
-
codonPython.file_utils.
file_search
(path='.', doctype='csv', like=[''], strict=False)¶ This function creates a list of all files of a certain type, satisfying the criteria outlined in like = […] parameter. The function only searches for files in the specified folder of the current working directory that is set by the user.
- Parameters
path (string) – Path to a folder in the current working directory default = ‘.’, i.e. current working directory folder
doctype (string) – Document format to search for e.g. ‘csv’ or ‘xlsx’ default = ‘csv’
like (list) – A list of words to filter the file search on default = [‘’], i.e. no filter
strict (bool) – Set True to search for filenames containing all words from ‘like’ list ( default = False
- Returns
- Return type
list
Examples
>>> file_search(doctype = 'md') ['README.md', 'CONTRIBUTING.md']
>>> file_search(doctype = 'md', like = ['READ']) ['README.md']
-
codonPython.file_utils.
import_files
(path='.', doctype='csv', sheet='Sheet1', subdir=False, like=[''], strict=False)¶ This function imports all documents of a given format to a dictionary and returns this dictionary, keeping original file names.
- Parameters
path (string) – Path to a folder in the current working directory default = ‘.’, i.e. current working directory folder
doctype (string) – Document format to search for e.g. ‘csv’ or ‘xlsx’ default = ‘csv’
sheet (string) – Sheet name of the xlsx file default = ‘Sheet1’
subdir (bool) – True to allow download all files, including the subdirectories default = False
like (list) – A list of words to filter the file search on default = [‘’], i.e. no filter
strict (bool) – Set True to search for filenames containing all words from ‘like’ list default = False
- Returns
out
- Return type
dict
Examples
‘>>> import_files()’
File Data_AprF_2019 is successfully imported
File Data_AugF_2019 is successfully imported
File Data_JulF_2019 is successfully imported
File Data_JunF_2019_v1 is successfully imported
File Data_MayF_2019 is successfully imported
File Data_SepP_2019 is successfully imported
‘>>> import_files(like = [‘Aug’,’Sep’])’
File Data_AugF_2019 is successfully imported
File Data_SepP_2019 is successfully imported
codonPython.mesh module¶
-
class
codonPython.mesh.
MESHConnection
(mailbox: str, password: str, api_shared_key: str, cert_loc: str, key_loc: str, base_ca_loc: str, root_url: str = 'https://mesh-sync.national.ncrs.nhs.uk', org: str = 'NHS Digital')¶ Bases:
object
Class for handling MESH API interactions.
- Parameters
mailbox (string) – The MESH ID of the mailbox this client is for
password (string) – The password to this mailbox
api_shared_key (string) – The shared API key for the MESH environment the mailbox is in
cert_loc (string) – Path to the MESH API certificate location
key_loc (string) – Path to the MESH API certificate private key location
base_ca_loc (string) – Path to the base MESH certificate authority certificate bundle. Set to False to disable inbound SSL checks if necessary
root_url (string, default = “https://mesh-sync.national.ncrs.nhs.uk”) – Root MESH URL. Default value is the live MESH service
org (string, default = "NHS Digital") – Name of organisation owning the mailbox
-
check_authentication
() → bool¶ Check authentication with the MESH API. This should be done at the start of any session (per the API docs)
- Returns
Indicates if authentication was successful or not
- Return type
bool
- Raises
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.check_authentication() True
-
send_file
(dest_mailbox: str, message_location: str, workflow_id: str, message_subject: str = None, message_id: str = None, process_id: str = None, compress_message: bool = True, encrypted: bool = False)¶ Send a file to the MESH API. This will automatically chunk the message if required, splitting into chunks at 80MB (MESH API has a chunk size limit of 100MB). If required, this will also compress the message before transmission using gzip.
- Parameters
dest_mailbox (string) – MESH Mailbox ID of the recipient
message_location (string) – Path to the readable file to send as a message
workflow_id (string) – DTS Workflow ID
message_subject (string, default = None) – Optional subject line to use for the message, for SMTP (email) messages.
message_id (string, default = None) – Optional local identifier for the message. Required to track the message later.
process_id (string, default = None) – Optional process ID for the MESH message. Currently not used in MESH, but included to ensure future compatibility.
compress_message (boolean, default = True) – Indicates if the message should be compressed. If true, then the message will be compressed using gzip before sending to MESH.
encrypted (boolean, default = False) – Indicates if the file to send has been encrypted. This is solely used to pass a flag to MESH and does not encrypt the file or otherwise alter processing.
- Returns
Dictionary of returned values from the MESH API
messageID (str): value of the MESH internal ID assigned to the sent message
- Return type
dict
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHInvalidRecipient – The mailbox ID provided is not a valid recipient for this message
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.send_file("TEST", 'c:/test/test.txt', 'test_flow') {'messageID': '20200211115928515346_9359E2'}
-
send_message
(dest_mailbox: str, message: bytes, filename: str, workflow_id: str, message_subject: str = None, message_id: str = None, process_id: str = None, compress_message: bool = True, encrypted: bool = False)¶ Send a message to the MESH API. This will automatically chunk the message if required, splitting into chunks at 80MB (MESH API has a chunk size limit of 100MB). If required, this will also compress the message before transmission using gzip.
- Parameters
dest_mailbox (string) – MESH Mailbox ID of the recipient
message (bytes) – Bytes representation of the file to transmit
filename (string) – Original filename for the message being transmitted
workflow_id (string) – DTS Workflow ID
message_subject (string, default = None) – Optional subject line to use for the message, for SMTP (email) messages.
message_id (string, default = None) – Optional local identifier for the message. Required to track the message later.
process_id (string, default = None) – Optional process ID for the MESH message. Currently not used in MESH, but included to ensure future compatibility.
compress_message (boolean, default = True) – Indicates if the message should be compressed. If true, then the message will be compressed using gzip before sending to MESH.
encrypted (boolean, default = False) – Indicates if the file to send has been encrypted. This is solely used to pass a flag to MESH and does not encrypt the file or otherwise alter processing.
- Returns
Dictionary of returned values from the MESH API
messageID (str): value of the MESH internal ID assigned to the sent message
- Return type
dict
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHInvalidRecipient – The mailbox ID provided is not a valid recipient for this message
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.send_message("TEST", b'test', 'test.txt', 'test_flow') {'messageID': '20200211115928515346_9359E2'}
-
check_message_status
(message_id: str) → dict¶ Check status of a sent message.
- Parameters
message_id (string) – The local message ID, eg. as provided to send_message. Does NOT work with MESH Message IDs, only the local ID optionally provided on sending the message.
- Returns
The full response from the MESH API for this local ID. For details, consult the MESH API documentation
- Return type
dict
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHMultipleMatches – There are multiple messages in the outbox with this local ID
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.check_message_status(test) {"statusSuccess": ...}
-
check_inbox
() → list¶ Determine the MESH IDs of the contents of the inbox. This will return at most 500 entries, owing to the limitations of the API.
- Returns
The MESH IDs of the messages in the inbox (str)
- Return type
list
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.check_inbox() ["20200211115754892283_BC7B68", "20200211115928515346_9359E2"]
-
check_inbox_count
() → int¶ Determine how many messages are in the MESH mailbox to download.
- Returns
The number of messages ready to download
- Return type
int
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.check_inbox_count() 2
-
check_and_download
(save_folder: str = None, recursive: bool = True) → Optional[Generator[[dict, None], None]]¶ Download all messages in the inbox. This will automatically handle reconstructing chunked messages, and automatically decompress any messages which have Content-Encoding value of gzip. WARNING: each downloaded message will be fully reconstructed and decompressed if needed. This may cause issue for machines with very limited memory if there are very large files to download.
If save_folder is provided, then downloaded files will be saved into that folder with their original filenames (and non-delivery receipts will be saved there). This may cause issue if there are multiple files with the same filename.
If no save_folder is provided, then this function will return a generator which will yield each message in turn. When the generator yields a message, it will send an acknowledgement to the MESH API for the previous message; it is important that processing of the messages be complete and any required final outputs saved before this - once acknowledged a message cannot be downloaded from MESH again.
- Parameters
save_folder (string, default = None) –
If provided, the folder to save all downloaded files to when this function is called. The function will not yield intermediate results.
For data files, the file will be saved in this folder with its original filename.
For non-delivery reports, there will be a file created in the folder with filename ‘Non delivery report: (MESH message ID of failed delivery).txt’, and with content ‘Message not delivered. All known details below’ followed by the full dictionary of headers from the download response.
If not provided, then this function will instead yield results as documented below.
recursive (boolean, default = True) – If true, then this method will be called recursively so long as there are more than 500 messages in the inbox, the maximum number of messages the MESH API will provide IDs for at once. If false, then only one call will be made to retrieve inbox contents, and at most 500 messages will be downloaded.
- Yields
dict – Dictionary of details about the downloaded file.
filename (str): Filename of the original file (if provided).
contents (bytes): Contents of the file (reconstructed and decompressed if necessary).
headers (dict): Dictionary of headers returned by MESH on the initial download request. For full details see the MESH API documentation.
datafile (boolean): Indicates if this was a data file or a non-delivery report.
- Raises
MESHAuthenticationError – There was an authentication error accessing the inbox. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHUnknownError – There was an unexpected return status from the MESH API when accessing the inbox
MESHDownloadErrors – There were errors during the download process. This exception has the attribute ‘exceptions’, which contains a full list of messages which generated exceptions, along with the exception. This is only raised after completion of all non-error downloads, and downloads which raise an exception are not acknowledged to the MESH API.
Examples
>>> client.check_and_download("C:/Test Folder/") >>> for message in client.check_and_download(): >>> print(message) {'filename': 'test.txt', 'contents': b'test_message', 'headers': {...}, datafile: True} {'filename': 'test2.txt', 'contents': b'test_message_2', 'headers': {...}, datafile: True} {'filename': None, 'contents': b'', 'headers': {'Mex-Linkedmsgid': '1234567890', ...}, datafile: False}
-
download_message
(message_id: str, save_folder: str = None) → dict¶ Request a message from the MESH API. This will automatically handle reconstructing chunked messages, and automatically decompress any messages which have Content-Encoding value of gzip. WARNING: the full, reconstructed message will be held in memory, including after decompression. This may cause problems, if you are using the API to download very large files on a machine with very limited memory.
- Parameters
message_id (string) – The internal MESH ID of the message to download
save_folder (string, default = None) –
Optional, the folder to save the downloaded message to. If not provided, then the files are not saved.
For data files, the file will be saved in this folder with its original filename.
For non-delivery reports, there will be a file created in the folder with filename ‘Non delivery report: (MESH message ID of failed delivery).txt’, and with content ‘Message not delivered. All known details below’ followed by the full dictionary of headers from the download response.
- Returns
Dictionary of details about the downloaded file.
filename (str): Filename of the original file (if provided).
contents (bytes): Contents of the file (reconstructed and decompressed if necessary).
headers (dict): Dictionary of headers returned by MESH on the initial download request. For full details see the MESH API documentation.
datafile (boolean): Indicates if this was a data file or a non-delivery report.
- Return type
dict
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHMessageMissing – There is no message with the provided message ID in the mailbox
MESHMessageAlreadyDownloaded – The message with the provided message ID has already been downloaded and acknowledged
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.download_message("20200211115754892283_BC7B68", "C:/Test Folder/") {'filename': 'test.txt', 'contents': b'test_message', 'headers': {'Mex-Filename': 'test.txt', ...}, data: True} >>> client.download_message("20200211115754892283_BC7B69") {'filename': None, 'contents': b'', 'headers': {'Mex-Linkedmsgid': '1234567890', ...}, data: False}
-
ack_download_message
(message_id: str) → None¶ Send acknowledgement to the MESH API that a message has finished downloading. This should only be done after the message has successfully been saved - once sent, the message is remvoed from the MESH server. Per the API, this must be sent once a message has been successfully processed.
- Parameters
message_id (string) – The internal MESH ID of the downloaded message
- Raises
MESHAuthenticationError – There was an authentication error accessing this page. Either the SSL certificate used is invalid, or the client provided the wrong Mailbox ID, Password, or Shared Key.
MESHUnknownError – There was an unexpected return status from the MESH API
Examples
>>> client.ack_download_message("20200211115754892283_BC7B68")
Generate an authorization string as specified by the MESH API documentation v1.14
- Parameters
mailbox (string) – The mailbox ID to generate authorization for
password (string) – The password for the mailbox
api_shared_key (string) – The shared API key for the MESH environment the request is being made to
- Returns
The generated authentication string
- Return type
string
Examples
>>> generate_authorization("TEST_BOX", "TEST_PW", "TEST_KEY") "NHSMESH TEST_BOX:ccd54b96-ee41-4d34-9700-7f9ec63d0720:1:202002120857:763 ... 872c" >>> generate_authorization("NEW_BOX", "NEW_PW", "TEST_KEY") "NHSMESH NEW_BOX:662c4ffa-c85c-4858-bae8-7327e09aeeb5:1:202002120858:7f1 ... 0d95"
-
exception
codonPython.mesh.
MESHAuthenticationError
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
The MESH request authentication was invalid
-
exception
codonPython.mesh.
MESHDownloadErrors
(exceptions)¶ Bases:
Exception
There were errors downloading MESH messages
-
exception
codonPython.mesh.
MESHInvalidRecipient
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
The recipient is unknown or otherwise invalid
-
exception
codonPython.mesh.
MESHMessageAlreadyDownloaded
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
The MESH request has already been downloaded
-
exception
codonPython.mesh.
MESHMessageMissing
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
The message requested does not exist
-
exception
codonPython.mesh.
MESHMultipleMatches
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
There are multiple messages with the provided local ID
-
exception
codonPython.mesh.
MESHUnknownError
(*args, **kwargs)¶ Bases:
requests.exceptions.ConnectionError
There was an unknown error with the connection
Requirements¶
Using the MESH API requires a valid API certificate issued by DIR (for live environments) or Platforms (for development/test environments). Guidance on obtaining a certificate can be found in the MESH guidance hub. The module requires the certificate be in PEM format; the certificate enrolment tool produces a java keystore which the valid certificate can be extracted from if needs be. Due to limitations inherited from the Requests library, the private key must be unencrypted.
The keystore will also contain root authority certificates; these should also be extracted and combined into a certificate bundle for use in confirming the identity of the endpoint being communicated with. This check can be disabled, but this is not recommended.
Finally, use of the MESH API requires the API secret key, which can be requested from Platforms.
Example usage¶
Use of the MESH API will generally follow one of a few standard patterns.
Upload file pattern:
Check Authentication with the MESH API endpoint
Send one or more files (chunked if needed)
from codonPython.mesh import MESHConnection
mesh_client = MESHConnection(
mailbox = 'test'
password = 'test'
api_shared_key = 'test'
cert_loc = './certs/test.cert'
key_loc = './certs/test.key'
base_ca_loc = './certs/test.ca-bundle')
if mesh_client.check_authentication():
mesh_client.send_file('test_recipient', './test/test_20200224_1100.txt.dat', 'test_workflow')
Download file pattern:
Check Authentication with the MESH API endpoint
Request a list of files to download from the endpoint
Download and process each in turn (downloading chunked files if needed)
After each file has been successfully processed, send acknowledgement to the MESH API for that file
Repeat as needed until there are no more files which can be processed. Note that the MESH API will return at most 500 message IDs at a time.
from codonPython.mesh import MESHConnection
mesh_client = MESHConnection(
mailbox = 'test'
password = 'test'
api_shared_key = 'test'
cert_loc = './certs/test.cert'
key_loc = './certs/test.key'
base_ca_loc = './certs/test.ca-bundle')
if mesh_client.check_authentication():
# To save all messages to a folder
mesh_client.check_and_download('./inbox')
# To perform more complex processing on each
for message in mesh_client.check_and_download():
process(message)
# To perform the flow manually instead of using the check_and_download helper method
errors = []
inbox_messages = mesh_client.check_inbox()
for message_id in inbox_messages:
try:
message = mesh_client.download_message(message_id, './inbox')
process(message)
mesh_client.ack_download_message(message_id)
except Exception as e:
errors.append(e)
NB: The regular MESH client has strict restrictions on filename and type. The API does not have any such restrictions, however it is likely that the system files are being sent to expects files to be in this format. Unless you know otherwise files should be sent with .dat extension, with filename pattern Organisation_Date_Time.ext.dat where .ext is the original file extension.
codonPython.nhsd_colours module¶
-
codonPython.nhsd_colours.
nhsd_colours
()¶ Returns a dictionary full of the different official NHSD colours from the style guide: https://digital.nhs.uk/about-nhs-digital/corporate-information-and-documents/nhs-digital-style-guidelines/how-we-look/colour-palette
- Parameters
None –
- Returns
colour_dict – A dictionary containing sets of official NHS Digital branding colours (Hexidecimal format) and fonts.
- Return type
dict (Python dictionary)
-
codonPython.nhsd_colours.
nhsd_seaborn_style
()¶ Sets the seaborn style to be inline with NHSD guidlines. This means your graphs in Seaborn, or in Matplotlib will come out looking as per the NHSD style guide. Simply run this function.
- Parameters
None –
- Returns
- Return type
None
codonPython.nhsNumber module¶
-
codonPython.nhsNumber.
nhsNumberGenerator
(to_generate: int, random_state: int = None) → list¶ Generates up to 1M random NHS numbers compliant with modulus 11 checks as recorded in the data dictonary. https://www.datadictionary.nhs.uk/data_dictionary/attributes/n/nhs/nhs_number_de.asp?shownav=1
- Parameters
to_generate (int) – number of NHS numbers to generate
random_state (int, default : None) – Optional seed for random number generation, for testing and reproducibility.
- Returns
generated – List of randomly generated NHS numbers
- Return type
list
Examples
>>> nhsNumberGenerator(2, random_state=42) [8429141456, 2625792787]
-
codonPython.nhsNumber.
nhsNumberValidator
(number: int) → bool¶ Validate NHS Number according to modulus 11 checks as recorded in the data dictionary. https://www.datadictionary.nhs.uk/data_dictionary/attributes/n/nhs/nhs_number_de.asp?shownav=1
- Parameters
number (int) – 10 digit integer to validate.
- Returns
If the number passes modulus 11 checks a.k.a. is valid.
- Return type
bool
Examples
>>> nhsNumberValidator(8429141456) True >>> nhsNumberValidator(8429141457) False
codonPython.ODS_lookup module¶
-
codonPython.ODS_lookup.
get_addresses
(codes: Iterable[str]) → pandas.core.frame.DataFrame¶ Query the ODS (organisation data service) API for a series of org codes and return a data frame containing names and addresses. Invalid codes will cause a message to be printed but will otherwise be ignored, as an incomplete merge table is more useful than no table at all.
- Parameters
codes (list, ndarray or pd.Series) – 3 character organization codes to retrieve information for.
- Returns
Address information for the given org codes.
- Return type
DataFrame
Examples
>>> result = get_addresses(pd.Series(["X26"])) >>> result.reindex(columns=sorted(result.columns)) Org_AddrLn1 Org_Code Org_Country Org_Name Org_PostCode Org_Town 0 1 TREVELYAN SQUARE X26 ENGLAND NHS Digital LS1 6AE LEEDS
-
codonPython.ODS_lookup.
query_api
(code: str) → Dict¶ Query the ODS (organisation data service) API for a single org code and return the full JSON result. Full API docs can be found here: https://digital.nhs.uk/services/organisation-data-service/guidance-for-developers/organisation-endpoint
- Parameters
code (str) – 3 character organization code.
- Returns
The data returned from the API.
- Return type
dict
Examples
>>> result = query_api("X26") >>> result["Organisation"]["Name"] 'NHS DIGITAL' >>> result["Organisation"]["GeoLoc"]["Location"]["AddrLn1"] '1 TREVELYAN SQUARE'
codonPython.suppression module¶
-
codonPython.suppression.
central_suppression_method
(valuein: int, rc: str = '5', upper: int = 5000000000) → str¶ Suppresses and rounds values using the central suppression method.
If value is 0 then it will remain as 0. If value is 1-7 it will be suppressed and appear as 5. All other values will be rounded to the nearest 5.
- Parameters
valuein (int) – Metric value
rc (str) – Replacement character if value needs suppressing
upper (int) – Upper limit for suppression of numbers (5 billion)
- Returns
out – Suppressed value (5), 0 or rounded valuein if greater than 7
- Return type
str
Examples
>>> central_suppression_method(3) '5' >>> central_suppression_method(24) '25' >>> central_suppression_method(0) '0'
codonPython.tableFromSql module¶
-
codonPython.tableFromSql.
tableFromSql
(server: str, database: str, table_name: str, user: str = '', password: str = '', schema: str = None, index_col: str = None, coerce_float: bool = True, parse_dates: list = None, columns: list = None, chunksize: int = None)¶ Returns a SQL table in a DataFrame.
Convert a table stored in SQL Server 2016 into a pandas dataframe. Uses sqlalchemy and pandas.
- Parameters
server (string) – Name of the SQL server
database (string) – Name of the SQL database
user (string, default: "") – If verification is required, name of the user
password (string, default: "") – If verification is required, password of the user
table_name (string) – Name of SQL table in database.
schema (string, default : None) – Name of SQL schema in database to query (if database flavor supports this). Uses default schema if None (default).
index_col (string or list of strings, default : None) – Column(s) to set as index(MultiIndex).
coerce_float (boolean, default : True) – Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates (list or dict, default : None) –
List of column names to parse as dates.
Dict of {column_name: format string} where format string is strftime compatible in
case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.
columns (list, default : None) – List of column names to select from SQL table
chunksize (int, default : None) – If specified, returns an iterator where chunksize is the number of rows to include in each chunk.
- Returns
Dataframe of the table requested from sql server
- Return type
pd.DataFrame
Examples
# >>> tableFromSql(“myServer2”, “myDatabase2”, “myTable2”) # pd.DataFrame # >>> tableFromSql(“myServer”, “myDatabase”, “myTable”, schema=”specialSchema”, columns=[“col_1”, “col_3”]) # pd.DataFrame