<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
import fnmatch

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))
    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)
    if result.status_code != 200:
      raise Exception(("Failed to convert %s to internal id. Phenotips responded with HTTP status code: %s.  "
                      "Please check that the project and individual were previously created in Phenotips.") % (int_id, result.status_code))

    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
  uname=project_name+ '_view'
  return uname,pwd


<commit_msg>Added in a warning message to password serve method to users who download and use this as a local instance.<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
import fnmatch

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>,project_<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)
    if result.status_code != 200:
      raise Exception(("Failed to convert %s to internal id. Phenotips responded with HTTP status code: %s.  "
                      "Please check that the project and individual were previously created in Phenotips.") % (int_id, result.status_code))

    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
    
    WARNING: we relying on this simply method of authentication due to the protection awarded by
             the Broad firewall and closed ports and limited access to host machine. For those 
             using this system elsewhere we would suggest storing a unique hashed password
             in the database and this function could retrieve it from there and server, or atleast
             have a better password generation mechanism. Our current implementation was a first attempt
             and we plan to strengthen this further soon.
  '''
  pwd=project_name+project_name
  if not read_only:
    uname=project_name
    return uname,pwd
  uname=project_name+ '_view'
  return uname,pwd



{'fraction_non_alphanumeric': 0.07243491577335376, 'fraction_numerical': 0.003675344563552833, 'mean_word_length': 4.41542288557214, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5510399', 'n_tokens_mistral': 2089, 'n_tokens_neox': 2003, 'n_words': 534}