• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python redcap.Project类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中redcap.Project的典型用法代码示例。如果您正苦于以下问题:Python Project类的具体用法?Python Project怎么用?Python Project使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Project类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: setUp

 def setUp(self):
     self.url = 'https://redcap.vanderbilt.edu/api/'
     self.bad_url = 'https://redcap.vanderbilt.edu/api'
     self.reg_token = '8E66DB6844D58E990075AFB51658A002'
     self.long_proj = Project(self.url, '1387872621BBF1C17CC47FD8AE25FF54')
     self.reg_proj = Project(self.url, self.reg_token)
     self.ssl_proj = Project(self.url, self.reg_token,
         verify_ssl=False)
开发者ID:thephillipsequation,项目名称:PyCap,代码行数:8,代码来源:test_project.py


示例2: extraer_redcap

def extraer_redcap(URL, API_KEY , VARIABLES_REDCap):
    
    from redcap import Project, RedcapError
    project = Project(URL, API_KEY)
    fields_of_interest = VARIABLES_REDCap
    subset = project.export_records(fields=fields_of_interest)

    return subset
开发者ID:aandresalvarez,项目名称:Caucaseco,代码行数:8,代码来源:CriaderosMarzo.py


示例3: create_projects

    def create_projects(self):
        self.add_long_project_response()
        self.add_normalproject_response()
        self.add_ssl_project()
        self.add_survey_project()

        self.long_proj = Project(self.long_proj_url, self.reg_token)
        self.reg_proj = Project(self.normal_proj_url, self.reg_token)
        self.ssl_proj = Project(self.ssl_proj_url, self.reg_token, verify_ssl=False)
        self.survey_proj = Project(self.survey_proj_url, self.reg_token)
开发者ID:redcap-tools,项目名称:PyCap,代码行数:10,代码来源:test_project.py


示例4: extraer_redcap

def extraer_redcap(URL, API_KEY , VARIABLES_REDCap):
    
    from redcap import Project, RedcapError
##    URL = 'http://claimproject.com/redcap570/api/'
##    API_KEY_SOCIODEMOGRAFICA = 'FC8BD5EE83AE0DECD2BF247031BD028E'
##    API_KEY_SINTOMAS ='744F5C67890BDA39B9CC2B4A9CE77F12';
    project = Project(URL, API_KEY)
    fields_of_interest = VARIABLES_REDCap
    subset = project.export_records(fields=fields_of_interest)

    return subset
开发者ID:aandresalvarez,项目名称:Caucaseco,代码行数:11,代码来源:google_maps_pointsV2.py


示例5: __init__

 def __init__(self,  key, url, table_name, connection='', driver='',server='',database='',  dev=False, project='',  records='', forms = []):
     self.connection                      = connection
     self.key                                  = key
     self.url                                  = url
     #self.server                                  = server
     #self.driver                          = driver
     #self.database                           = database
     self.dev                                 = dev
     self.table_name                         = table_name
     self.records                            = records
     self.forms                              = forms
     if self.dev == False:
         self.project                        = Project(self.url, self.key)
         print 'Production Environment'
     if self.dev == True:
         self.project                        = Project(self.url,self.key, verify_ssl=False)
         print 'Dev Environment'
开发者ID:thephillipsequation,项目名称:NTSR_redcap,代码行数:17,代码来源:NTSR_redcap.py


示例6: RCDB

class RCDB(DB):
    """Class representing a redcap database"""

    def __init__(self, url, api, initial_fields):
        self.proj = Project(url, api)
        self.make_df(initial_fields)

    def make_df(self, fields):
        csv = StringIO(self.proj.export_records(fields=fields, format='csv'))
        self.df = pd.read_csv(csv, index_col=self.proj.def_field)
开发者ID:sburns,项目名称:red-light,代码行数:10,代码来源:backend.py


示例7: __init__

    def __init__(self, redcap_uri, token, verify_ssl=True):
        self.redcap_uri = redcap_uri
        msg = 'Initializing redcap interface for: ' + redcap_uri
        logger.info(msg)
        self.token = token
        self.verify_ssl = verify_ssl

        try:
            self.project = Project(redcap_uri, token, "", verify_ssl)
            logger.info("redcap interface initialzed")
        except (RequestException, RedcapError) as e:
            logger.exception(e.message)
            raise
开发者ID:indera,项目名称:redi,代码行数:13,代码来源:redcapClient.py


示例8: RedcapClient

class RedcapClient(object):
    """ Client for a REDCap server.

    :param redcap_uri: URI for to REDCap server's API
    :param token: API Token for a REDCap project.
    :param verify_ssl: verify the SSL certificate? (default: True)
    :raises RedcapError: if we failed to get the project's metadata
    :raises RequestException: if some other network-related failure occurs
    """
    def __init__(self, redcap_uri, token, verify_ssl=True):
        self.redcap_uri = redcap_uri
        msg = 'Initializing redcap interface for: ' + redcap_uri
        logger.info(msg)
        self.token = token
        self.verify_ssl = verify_ssl

        try:
            self.project = Project(redcap_uri, token, "", verify_ssl)
            logger.info("redcap interface initialzed")
        except (RequestException, RedcapError) as e:
            logger.exception(e.message)
            raise

    def get_data_from_redcap(
            self,
            records_to_fetch=None,
            events_to_fetch=None,
            fields_to_fetch=None,
            forms_to_fetch=None,
            return_format='xml'):
        """ Exports REDCap records.

        :param records_to_fetch: if specified, only includes records in this
            list. Otherwise, includes all records.
        :type records_to_fetch: list or None

        :param events_to_fetch: if specified, only includes events in this list.
            Otherwise, includes all events.
        :type events_to_fetch: list or None

        :param fields_to_fetch: if specified, only includes fields in this list.
            Otherwise, includes all fields
        :type fields_to_fetch: list or None

        :param forms_to_fetch: if specified, only includes forms in this list.
            Otherwise, includes all forms.
        :type forms_to_fetch: list or None

        :param return_format: specifies the format of the REDCap response
            (default: xml)

        :return: response
        """
        logger.info('getting data from redcap')
        try:
            response = self.project.export_records(
                records=records_to_fetch,
                events=events_to_fetch,
                fields=fields_to_fetch,
                forms=forms_to_fetch,
                format=return_format)
        except RedcapError as e:
            logger.debug(e.message)
        return response

    def send_data_to_redcap(self, data, overwrite=False):
        """ Sends records to REDCap.

        :param list of dict objects data: records to send.
        :param bool overwrite: treat blank values as intentional?
            (default: False) When sending a record, if a field is blank, by
            default REDCap will not overwrite any existing value with a blank.
        :return: response
        :raises RedcapError: if failed to send records for any reason.
        """
        overwrite_value = 'overwrite' if overwrite else 'normal'

        try:
            response = self.project.import_records(data,
                                                   overwrite=overwrite_value)
            return response
        except RedcapError as e:
            logger.debug(e.message)
            raise
开发者ID:indera,项目名称:redi,代码行数:84,代码来源:redcapClient.py


示例9: RedcapClient

class RedcapClient(object):
    """ Client for a REDCap server.

    :param redcap_uri: URI for to REDCap server's API
    :param token: API Token for a REDCap project.
    :param verify_ssl: verify the SSL certificate? (default: True)
    :raises RedcapError: if we failed to get the project's metadata
    :raises RequestException: if some other network-related failure occurs
    """
    def __init__(self, redcap_uri, token, verify_ssl=True):
        self.redcap_uri = redcap_uri
        msg = 'Initializing redcap interface for: ' + redcap_uri
        logger.info(msg)
        self.token = token
        self.verify_ssl = verify_ssl

        try:
            self.project = Project(redcap_uri, token, "", verify_ssl)
            logger.info("redcap interface initialzed")
        except (RequestException, RedcapError) as e:
            logger.exception(e.message)
            raise

    def get_data_from_redcap(
            self,
            records_to_fetch=None,
            events_to_fetch=None,
            fields_to_fetch=None,
            forms_to_fetch=None,
            return_format='xml'):
        """ Exports REDCap records.

        :param records_to_fetch: if specified, only includes records in this
            list. Otherwise, includes all records.
        :type records_to_fetch: list or None

        :param events_to_fetch: if specified, only includes events in this list.
            Otherwise, includes all events.
        :type events_to_fetch: list or None

        :param fields_to_fetch: if specified, only includes fields in this list.
            Otherwise, includes all fields
        :type fields_to_fetch: list or None

        :param forms_to_fetch: if specified, only includes forms in this list.
            Otherwise, includes all forms.
        :type forms_to_fetch: list or None

        :param return_format: specifies the format of the REDCap response
            (default: xml)

        :return: response
        """
        logger.info('getting data from redcap')
        try:
            response = self.project.export_records(
                records=records_to_fetch,
                events=events_to_fetch,
                fields=fields_to_fetch,
                forms=forms_to_fetch,
                format=return_format)
        except RedcapError as e:
            logger.debug(e.message)
        return response

    def send_data_to_redcap(self, data, max_retry_count, overwrite=False,
        retry_count=0):
        """ Sends records to REDCap.

        :param list of dict objects data: records to send.
        :param bool overwrite: treat blank values as intentional?
            (default: False) When sending a record, if a field is blank, by
            default REDCap will not overwrite any existing value with a blank.
        :return: response
        :raises RedcapError: if failed to send records for any reason.
        :If MaxRetryError is caught, the function will try resending the same
         data for a maximum of max_retry_count times before exitting. For each
         attempt the wait time before sending is (the_attempt_no * 6)
        """
        overwrite_value = 'overwrite' if overwrite else 'normal'

        try:
            # The following line simulates github issue #108:
            # raise MaxRetryError('', 'localhost:8998', None)
            # The following line simulates 
            #raise NewConnectionError('localhost:8998', 443)
            response = self.project.import_records(data,
                overwrite=overwrite_value)
            return response
        except (MaxRetryError, NewConnectionError, ConnectionError) as e:
            logger.error("Exception encountered: ", exc_info = True)
            logger.debug(str(e.message) + ", Attempt no.: " + str(retry_count))
            if (retry_count == max_retry_count):
                message = "Exiting since network connection timed out after"\
                " reaching the maximum retry limit for resending data."
                logger.debug(message)
                sys.exit(message)
            # wait for some time before resending data
            time.sleep(retry_count*6)
            self.send_data_to_redcap(data, max_retry_count, 'overwrite',
#.........这里部分代码省略.........
开发者ID:ash-kai,项目名称:redi,代码行数:101,代码来源:redcapClient.py


示例10: print

    for field_name in field_list:
        if (isinstance(in_row[i], str)):
            val_str = in_row[i]
        else:
            val_str = in_row[i].strftime("%Y-%m-%d %H:%M:%S")
        out_row[field_name] = val_str
        i += 1
    out_row.update( fixed_field_list )
    out_rows.append(out_row)
    in_row = cur.fetchone()

print ( "Read ", len(out_rows), " records from sql database: ", config["sql-database"] )

conn.close()

from redcap import Project, RedcapError
URL = (config["redcapURL"])
API_KEY = (config["redcapApiKey"])
project = Project(URL, API_KEY)


batch_start = 0
while ( batch_start < len(out_rows)):
    response = project.import_records(out_rows[batch_start : batch_start + batch_count])
    if ( batch_start + batch_count <= len(out_rows)):
        print ("Added a batch of ", batch_count, " records")
    else:
        print ("Added a batch of ", len(out_rows) - batch_start, " records")
    batch_start += batch_count

开发者ID:tberla,项目名称:RedCap-tools,代码行数:29,代码来源:sql_to_redcap.py


示例11: main

def main():

    parser = argparse.ArgumentParser(description="Read some data from a REDCap Project")
    parser.add_argument(
        "--token",
        dest="token",
        default="",
        required=True,
        help="Specify the authentication/authorization token that will provide access to the REDCap project",
    )
    parser.add_argument(
        "--url", dest="url", default="", required=True, help="Specify the url of the REDCap server to connect with"
    )
    parser.add_argument(
        "--verify_ssl",
        dest="verify_ssl",
        default=True,
        help="Specify whether the SSL cert of the REDCap server should be checked",
    )
    parser.add_argument(
        "-i", "--import_data", dest="import_data", default="", help="Specify the input data file to load into REDCap"
    )
    parser.add_argument(
        "-f",
        "--forms",
        dest="forms",
        default="",
        help="Specify a list of forms, separated by spaces, for which data should be returned.",
    )
    parser.add_argument(
        "-t",
        "--type",
        choices=["json", "csv", "xml"],
        dest="data_type",
        default="csv",
        help="Specify the file type used as input or output. Valid types: json, csv, xml",
    )
    parser.add_argument(
        "--fields",
        dest="fields",
        default="",
        help="Specify a list of fields, separated by space or comma, for which data should be returned.",
    )
    parser.add_argument(
        "-e",
        "--events",
        dest="events",
        default="",
        help="Specify a list of events, separated by space or comma, for which data should be returned.",
    )
    parser.add_argument(
        "-r",
        "--records",
        dest="records",
        default="",
        help="Specify a list of records, separated by spaces or comma, for which data should be returned.",
    )
    # Additional verbosity
    parser.add_argument(
        "-d",
        "--debug",
        dest="loglevel",
        default=logging.WARNING,
        const=logging.DEBUG,
        action="store_const",
        help="Print even more detailed output",
    )
    parser.add_argument(
        "-v", "--verbose", dest="loglevel", const=logging.INFO, action="store_const", help="Print detailed output"
    )

    # prepare the arguments we were given
    args = vars(parser.parse_args())

    # configure logger
    logging.basicConfig(level=args["loglevel"])

    # According to http://pycap.readthedocs.org/en/latest/api.html
    # allowed data_types are: csv, json, xml
    data_type = args["data_type"]

    # Turn the 'verify_ssl' parameter into the truth value we need to make a
    # REDCap connection
    if args["verify_ssl"] == "y":
        args["verify_ssl"] = True
    elif args["verify_ssl"] == "n":
        args["verify_ssl"] = False
    else:
        args["verify_ssl"] = True

    # Attempt to connect to the REDCap project
    try:
        project = Project(args["url"], args["token"], "", args["verify_ssl"])
    except:

        # Produce varying levels of output corresponding to loglevel
        logging.debug(traceback.format_list(traceback.extract_tb(sys.exc_traceback)))
        logging.info(traceback.format_exc())
        logging.error(
            "Cannot connect to project at "
#.........这里部分代码省略.........
开发者ID:ctsit,项目名称:redcap_cli,代码行数:101,代码来源:redcap_records.py


示例12: setUp

 def setUp(self):
     self.url = 'https://redcap.vanderbilt.edu/api/'
     self.long_proj = Project(self.url, '1387872621BBF1C17CC47FD8AE25FF54')
     self.reg_proj = Project(self.url, '8E66DB6844D58E990075AFB51658A002')
开发者ID:Varadharajan88,项目名称:PyCap,代码行数:4,代码来源:test_project.py


示例13: Project

__author__ = 'od0236'

from redcap import Project, RedcapError
URL = 'http://redcap.dfdev.biz/redcap/api/'
API_KEY = 'B882733EE6C4FC181C7591DB30D07CF5'
project = Project(URL, API_KEY)

print (project.field_names)


import json
import fileinput

json_in = ""
for line in fileinput.input():
    json_in = json_in + line

json_in_dict = json.loads(json_in)

response = project.import_records(json_in_dict)

print (json_in_dict)
开发者ID:tberla,项目名称:RedCap-tools,代码行数:22,代码来源:pyCapTest.py


示例14: redcap_connection

class redcap_connection(object):
    '''Contains properties and values necessary to transform REDCap projects into SQL Database tables
    Required parameters:
            url   --> this should be the url of your redcap database. Usually of the form https://redcap.host/api/
            key  --> this is the API key generated within redcap itself. If you do not have one contact your system administrator for more information about gaining access
            table_name  --> this is the SQL table name you will be inserting into your ODBC SQL database. 
    Optional parameters:
        **WARNING: when this flag is set to True you are susceptible to a man-in the middle attack, use at your own risk**
        dev = True  --> This will not verify ssl and assumes you are working in a dev environment (or one without an up to date ssl certificate)    
        dev = False -->  This setting will require an ssl certificate from the hosted redcap database
            
        records
        forms
        '''
    def __init__(self,  key, url, table_name, connection='', driver='',server='',database='',  dev=False, project='',  records='', forms = []):
        self.connection                      = connection
        self.key                                  = key
        self.url                                  = url
        #self.server                                  = server
        #self.driver                          = driver
        #self.database                           = database
        self.dev                                 = dev
        self.table_name                         = table_name
        self.records                            = records
        self.forms                              = forms
        if self.dev == False:
            self.project                        = Project(self.url, self.key)
            print 'Production Environment'
        if self.dev == True:
            self.project                        = Project(self.url,self.key, verify_ssl=False)
            print 'Dev Environment'
       

            
        
                
            
    def schema(self, participant_id= True):
        '''Processes the REDCap metadata to generate sql schema and creates a table reflecting that schema in your ODBC destination
        PARAMS:
            participant_id:
                    If flagged true (default) it will make the first column in your schema = participant_id [varchar(50)]
        '''
        #Exports metadata for the forms specifed. If no forms are specified all forms are included. 
        self.metadata = self.project.export_metadata(forms=self.forms)
        
        #These if statements check if table name is given and handles the participant_id flag for inclusion of that field in the database
        if self.table_name:
            if participant_id == True:
                #participant ids are handled differently than the other columns because it is typically used as a primary key and should be included on tables created for all forms. 
                participant_id_string = '''[participant_id][varchar](500) PRIMARY KEY, \n'''
                #If the table name already exists in the database it is dropped so the new table may be created
                sqlstring = '''IF EXISTS (
                SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].['''+self.table_name+''']') AND type in (N'U')) 
                DROP TABLE [dbo].[''' + self.table_name + ''']
                CREATE TABLE [dbo].[''' + self.table_name + '''](\n''' + participant_id_string
        #In the case that participant_id is not set to True the same process as above occurs but the participant_id is not added as the first column in the table
        if participant_id != True:
            sqlstring = '''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].['''+self.table_name+''']') AND type in (N'U')) 
                        DROP TABLE [dbo].[''' + self.table_name + '''] CREATE TABLE [dbo].[''' + self.table_name + '''](\n'''
            print 'participant_id != True'
            return
        
        #Escapes function if table_name not provided
        elif not self.table_name:
            print "Please provide a table name"
            return
    
 
   
        #This for loop reads the metadata and adds the appropriate column name and Microsoft SQL Server 2008 R2 datatype, 
        #these datatypes may require modification if destination server is not SQL Server 2008 or compatible, but that modification should be relatively painless. 
        
        
        #Loop iterations
        #1.) Iterate through all forms specified
        #2.)For each form , iterate through its metadata and process each column based off of field_type
        for form in self.forms:
        #Redcap metadata should be passed to this function as a list of dictionaries
            for dictionary in self.metadata:
                #This if statement verifies that only wanted forms are processed in the schema
                if dictionary['form_name'] == form:
                    #REDCap checkbox fields require that their output be stored as multiple columns, these next few lines create appropriate columns for each checkbox column
                    if dictionary['field_type'] == 'checkbox':
                        ls = []
                        #checkbox choices are split and processed from the string first by \\n which is a newline character to form a ls of items in the form ['1, Native-American', '2, Black']                    
                        ls = dictionary['select_choices_or_calculations'].split('|')
                        for i in ls:
                            #for each choice value the field_name + a choice number are given as strings, comments could be injected into the sql code here if desired as easy reminders of what the checkboxes correlate to
                            #for example sqlstring = sqlstring + '/*' + dictionary['select_choices_or_calculations'] + '*/'
                            sqlstring = sqlstring + '['+ dictionary['field_name'] + '___'+ str(int(i.split(",")[0])) + '] [Float] NULL, \n'
                            
                    #Descriptive fields are ignored as they contain no record information
                    elif dictionary['field_type'] == 'descriptive':
                        continue
                        
                    #This block of elif statements handles date / datetime fields in redcap by calling them as datetime sql 
                    elif dictionary['field_type'] == 'text' and dictionary['text_validation_type_or_show_slider_number'] == 'date_ymd':
                        sqlstring = sqlstring + '[' +dictionary['field_name'] + '][datetime] NULL, \n'
                    elif dictionary['field_type'] == 'text' and dictionary['text_validation_type_or_show_slider_number'] == 'date_mdy':
#.........这里部分代码省略.........
开发者ID:thephillipsequation,项目名称:NTSR_redcap,代码行数:101,代码来源:NTSR_redcap.py


示例15: Project


import re
import time

from redcap import Project
from ebrl.mail import mail
from ebrl.config import rc as redcap_keys

URL = 'https://redcap.vanderbilt.edu/api/'
TO = ('[email protected]','[email protected]', '[email protected]')
#TO = ('[email protected]',)

if __name__ == '__main__':

    project = Project(URL, redcap_keys['rc'])    
    
    #  Fields we want from redcap
    fields = ['scan_num', 'im_date', 'eprime_number']

    data = project.export_records(fields=fields)
    
    #  Sort on behav id
    data.sort(key=lambda x: int(x['participant_id'].split('_')[0]))

    body = """<html><body><h2>RCV Redcap database as of {time}</h2>
    
<table border="1">
<tr><th>{0}</th><th>{1}</th><th>{2}</th></tr>
{d}
</table>
开发者ID:sburns,项目名称:ebrl_emails,代码行数:29,代码来源:rcv.py


示例16: main

def main():

    parser = argparse.ArgumentParser(
        description='Read some data from a REDCap Project')
    parser.add_argument(
        '--token',
        dest='token',
        default='',
        required=True,
        help='Specify the authentication/authorization token that will provide access to the REDCap project')
    parser.add_argument(
        '--url',
        dest='url',
        default='',
        required=True,
        help='Specify the url of the REDCap server to connect with')
    parser.add_argument(
        '--verify_ssl',
        dest='verify_ssl',
        default=True,
        help='Specify whether the SSL cert of the REDCap server should be checked')
    parser.add_argument('-i', '--import_data', dest='import_data', default='',
                        help='Specify the input data file to load into REDCap')
    parser.add_argument(
        '-f',
        '--forms',
        dest='forms',
        default='',
        help='Specify a list of forms, separated by spaces, for which data should be returned.')
    parser.add_argument(
        '-t',
        '--type',
        choices=['json', 'csv', 'xml'],
        dest='data_type',
        default='csv',
        help='Specify the file type used as input or output. Valid types: json, csv, xml')
    parser.add_argument(
        '--fields',
        dest='fields',
        default='',
        help='Specify a list of fields, separated by spaces, for which data should be returned.')
    parser.add_argument(
        '-e',
        '--events',
        dest='events',
        default='',
        help='Specify a list of events, separated by spaces, for which data should be returned.')
    parser.add_argument(
        '-r',
        '--records',
        dest='records',
        default='',
        help='Specify a list of records, separated by spaces, for which data should be returned.')

    # prepare the arguments we were given
    args = vars(parser.parse_args())

    # According to http://pycap.readthedocs.org/en/latest/api.html
    # allowed data_types are: csv, json, xml
    data_type = args['data_type']

    # Turn the 'verify_ssl' parameter into the truth value we need to make a
    # REDCap connection
    if args['verify_ssl'] == 'y':
        args['verify_ssl'] = True
    else:
        args['verify_ssl'] = False

    # Attempt to connect to the REDCap project
    try:
        project = Project(args['url'], args['token'], "", args['verify_ssl'])
    except:
        print "Cannot connect to project at " + args['url'] + ' with token ' + args['token']
        quit()

    # either we export data...
    if args['import_data'] == '':
        my_forms = args['forms'].split()
        my_fields = args['fields'].split()
        my_events = args['events'].split()
        my_records = args['records'].split()
        data = project.export_records(
            forms=my_forms,
            format = data_type,
            fields=my_fields,
            events=my_events,
            records=my_records,
            event_name='unique')
        if 'json' == data_type:
            print json.dumps(data, ensure_ascii=False)
        else:
            print str(data)
    else:
        # ...or we import data
        file = args['import_data']
        try:
            input = open(file, 'r')
        except IOError:
            print "Cannot open file " + file
            quit()
#.........这里部分代码省略.........
开发者ID:indera,项目名称:redi,代码行数:101,代码来源:redcap_records.py


示例17: csv_from_redcap

def csv_from_redcap(KEY):
    API_URL = os.environ['API_URL']
    API_KEY= os.environ[KEY]
    rc_fields=['record_id','experiment_xnat','scan_xnat','scan_sd_xnat','process_name_xnat','quality_control_complete']
    p = Project(API_URL, API_KEY)
    return p.export_records(fields=rc_fields,format='csv')
开发者ID:VUIIS,项目名称:zald_report,代码行数:6,代码来源:ExtractDataRedcap.py


示例18: __init__

 def __init__(self, url, api, initial_fields):
     self.proj = Project(url, api)
     self.make_df(initial_fields)
开发者ID:sburns,项目名称:red-light,代码行数:3,代码来源:backend.py


示例19: token

import datetime

"""
in `project_info.txt` store
your token (first line)
REDCap-specific API URL (second line)
"""
fh = open('project_info.txt','r')
token = fh.next().strip()
apiurl = fh.next().strip()
fh.close()

"""
The heavy lifting is done in 2 lines of code
using Scott Burns' awesome PyCap module
"""
bpcoll = Project( apiurl, token )
bpcoll_csvrecords = bpcoll.export_records( format='csv' )

"""
Save a snapshot of the blood pressure data to a csv
"""
filenowname = 'bpcoll_{0}.csv'.format( datetime.datetime.today().strftime('%Y%m%d_%H%M') )
filecurrentname = 'bpcoll_current.csv'
fhout = open( filenowname, 'w' )
fhout.write( bpcoll_csvrecords )
fhout.close()
fhout = open( filecurrentname, 'w' )
fhout.write( bpcoll_csvrecords )
fhout.close()
开发者ID:firaswehbe,项目名称:bp-redcap-coll,代码行数:30,代码来源:getbpcoll.py


示例20: main

def main():

    parser = argparse.ArgumentParser(
        description='Read project metadata from a REDCap Project')
    parser.add_argument(
        '--token',
        dest='token',
        default='',
        required=True,
        help='Specify the authentication/authorization token that will provide access to the REDCap project')
    parser.add_argument(
        '--url',
        dest='url',
        default='',
        required=True,
        help='Specify the url of the REDCap server to connect with')
    parser.add_argument(
        '--verify_ssl',
        dest='verify_ssl',
        default=True,
        help='Specify whether the SSL cert of the REDCap server should be checked')
    # parser.add_argument(
    #     '-f',
    #     '--forms',
    #     dest='forms',
    #     default='',
    #     help='Specify a list of forms, separated by spaces, for which metadata should be returned.')
    # parser.add_argument(
    #     '--fields',
    #     dest='fields',
    #     default='',
    #     help='Specify a list of fields, separated by spaces, for which metadata should be returned.')
    # Additional verbosity
    parser.add_argument(
        '-d',
        '--debug',
        dest="loglevel",
        default=logging.WARNING,
        const=logging.DEBUG,
        action="store_const",
        help="Print even more detailed output"
        )
    parser.add_argument(
        '-v',
        '--verbose',
        dest="loglevel",
        const=logging.INFO,
        action="store_const",
        help="Print detailed output"
        )

    # prepare the arguments we were given
    args = vars(parser.parse_args())

    # configure logger
    logging.basicConfig(level=args['loglevel'])

    # prepare the arguments we were given
    args = vars(parser.parse_args())

    # Turn the 'verify_ssl' parameter into the truth value we need to make a
    # REDCap connection
    if args['verify_ssl'] == 'y':
        args['verify_ssl'] = True
    elif args['verify_ssl'] == 'n':
        args['verify_ssl'] = False
    else:
        args['verify_ssl'] = True

    # Attempt to connect to the REDCap project
    try:
        project = Project(args['url'], args['token'], "", args['verify_ssl'])
    except:
        
        # Produce varying levels of output corresponding to loglevel
        logging.debug(traceback.format_list(traceback.extract_tb(sys.exc_traceback)))
        logging.info(traceback.format_exc())
        logging.error("Cannot connect to project at " + args['url'] + ' with token ' + args['token'] + "\nAdd '-d, --debug' flag for more info")
        
        quit()

    # my_forms = args['forms'].split()
    # my_fields = args['fields'].split()
    data = project.export_metadata(
        # forms=my_forms,
        # fields=my_fields,
        format='csv')
    print unicode(data)
开发者ID:ctsit,项目名称:redcap_cli,代码行数:88,代码来源:redcap_metadata.py



注:本文中的redcap.Project类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reddit.Reddit类代码示例发布时间:2022-05-26
下一篇:
Python redbaron.RedBaron类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap