<commit_before>import os
import logging
from django.conf import settings
import json
import urllib2
import base64
import requests
logger = logging.getLogger(__name__)
import sys
from xbrowse_server.base.models import Project
from django.shortcuts import get_object_or_404

def create_patient_record(individual_id,project_id,patient_details=None):
  '''
    Make a patient record:
  
    Create a patient record in phenotips.
    By convention username and password are project_id,project_idproject_id
    Authentication is protected by access to machine/localhost  
  
  '''
  uri = settings.PHENOPTIPS_HOST_NAME + '/bin/PhenoTips/OpenPatientRecord?create=true&eid=' + individual_id
  if patient_details is not None:
    uri += '&gender='+patient_details['gender']
  uname,pwd = get_uname_pwd_for_project(project_id)
  result,curr_session=do_authenticated_call_to_phenotips(uri,uname,pwd)
  if result is not None and result.status_code==200:
      print 'successfully created or updated patient',individual_id
      patient_eid = convert_internal_id_to_external_id(individual_id,uname,pwd)
      collaborator_username,collab_pwd=get_uname_pwd_for_project(project_id,read_only=True)
      add_read_only_user_to_phenotips_patient(collaborator_username,patient_eid)
  else:
      print 'error creating patient',individual_id,':',result
  
      

def do_authenticated_call_to_phenotips(url,uname,pwd,curr_session=None):
  '''
    Authenticates to phenotips, fetches (GET) given results and returns that
  '''
  try:
    if curr_session is None:
      s= requests.Session()
    else:
      s=curr_session
    result=s.get(url,auth=(uname,pwd))
    #password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    #request = urllib2.Request(url)
    #base64string = base64.encodestring('%s:%s' % (uname, pwd)).replace('\n', '')
    #request.add_header("Authorization", "Basic %s" % base64string)   
    #result = urllib2.urlopen(request)   
    return result,s
  except Exception as e:
    raise


def convert_internal_id_to_external_id(int_id,project_phenotips_uname,project_phenotips_pwd):
  '''
    To help process a translation of internal id to external id 
  '''
  try:
    url= os.path.join(settings.PHENOPTIPS_HOST_NAME,'rest/patients/eid/'+str(int_id))   
    result,curr_session = do_authenticated_call_to_phenotips(url,project_phenotips_uname,project_phenotips_pwd)
    #as_json = json.loads(result.read())
    as_json = result.json()
    return as_json['id']
  except Exception as e:
    print 'convert internal id error:',e
    logger.error('phenotips.views.convert_internal_id_to_external_id:'+str(e))
    raise
  

def get_uname_pwd_for_project(project_name,read_only=False):
  '''
    Return the username and password for this project. 
    If read_only flag is true, only a read-only username will be returned
  '''
  pwd=project_name+project_name
  if not read_only:
    uname=project_name
    return uname,pwd<commit_msg>refactoring and cleaning up old code continued<commit_after>import os
import logging
from django.conf import settings
import json
import urllib2
import base64
import requests
logger = logging.getLogger(__name__)
import sys
from xbrowse_server.base.models import Project
from django.shortcuts import get_object_or_404

def create_patient_record(individual_id,project_id,patient_details=None):
  '''
    Make a patient record:
  
    Create a patient record in phenotips.
    By convention username and password are <PASSWORD>
    Authentication is protected by access to machine/localhost  
  
  '''
  uri = settings.PHENOPTIPS_HOST_NAME + '/bin/PhenoTips/OpenPatientRecord?create=true&eid=' + individual_id
  if patient_details is not None:
    uri += '&gender='+patient_details['gender']
  uname,pwd = get_uname_pwd_for_project(project_id)
  result,curr_session=do_authenticated_call_to_phenotips(uri,uname,pwd)
  if result is not None and result.status_code==200:
      print 'successfully created or updated patient',individual_id
      patient_eid = convert_internal_id_to_external_id(individual_id,uname,pwd)
      collaborator_username,collab_pwd=get_uname_pwd_for_project(project_id,read_only=True)
      add_read_only_user_to_phenotips_patient(collaborator_username,patient_eid)
  else:
      print 'error creating patient',individual_id,':',result
  
      

def do_authenticated_call_to_phenotips(url,uname,pwd,curr_session=None):
  '''
    Authenticates to phenotips, fetches (GET) given results and returns that
  '''
  try:
    if curr_session is None:
      s= requests.Session()
    else:
      s=curr_session
    result=s.get(url,auth=(uname,pwd))
    return result,s
  except Exception as e:
    raise


def convert_internal_id_to_external_id(int_id,project_phenotips_uname,project_phenotips_pwd):
  '''
    To help process a translation of internal id to external id 
  '''
  try:
    url= os.path.join(settings.PHENOPTIPS_HOST_NAME,'rest/patients/eid/'+str(int_id))   
    result,curr_session = do_authenticated_call_to_phenotips(url,project_phenotips_uname,project_phenotips_pwd)
    as_json = result.json()
    return as_json['id']
  except Exception as e:
    print 'convert internal id error:',e
    logger.error('phenotips.views.convert_internal_id_to_external_id:'+str(e))
    raise
  

def get_uname_pwd_for_project(project_name,read_only=False):
  '''
    Return the username and password for this project. 
    If read_only flag is true, only a read-only username will be returned
  '''
  pwd=<PASSWORD>
  if not read_only:
    uname=project_name
    return uname,pwd
{'fraction_non_alphanumeric': 0.08413244074543152, 'fraction_numerical': 0.0048851094626379595, 'mean_word_length': 4.9697624190064795, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5380118', 'n_tokens_mistral': 1883, 'n_tokens_neox': 1825, 'n_words': 383}