<commit_before>#!/usr/bin/env python
# encoding: utf-8
"""
nationalrail.py

Python implementation for National Rail api (UK).
Author: <NAME>
"""
__VERSION__ = "1.0"

import sys
import httplib, urllib
import xml.dom.minidom
from xml2dict import fromstring

from settings import *
from requests import *

def doSoapCall(soapAction, args):
    """
    Method to make soap call given the url and proper xml.
    Have to do this, since unfortunately all python soap libs sucks.
    Looked at suds, soappy :(
    @param soapAction: Soap Action to use.
    @param host: National rail server host.
    @param url: URL to use for this soap action.
    @param xml: Request xml to be sent to the server.
    """
    hc = httplib.HTTPConnection(HOST)
    xml = SOAPACTION_REQUEST_MAPPING.get(soapAction, None)
    if not xml:
        print "Unable to find the request xml for the action %s" %soapAction
        sys.exit(1)
    xml = xml % args
    headers={
        'Host' : HOST,
        'Accept-Encoding' : 'gzip,deflate',
        'Content-Type' : 'application/soap+xml;charset=UTF-8;',
        'Content-Length' : len(xml),
        'User-Agent' : 'National Rail Enquiries for iPhone 1.2 (iPhone; iPhone OS 3.1.2)',
        'SOAPAction' : '"%s/%s"' %(SOAPACTION_URL_PREFIX, soapAction),
    }
    hc.request ('POST', API_URL, body=xml, headers=headers)
    resp = hc.getresponse()
    data = resp.read()
    if resp.status != 200:
        raise ValueError('Unable to receive expected data : %s, %s' % (resp.status, resp.reason))
    return parseXml(data, soapAction.replace("Request", "Result"))
        
def parseXml(ixml, tagName):
    """
    Method to parse the given xml for the given id and return the result as object
    minidom is used here.
    @param xml: Xml to parse
    @param tagName: Tag name to look for in the xml
    """
    doc = xml.dom.minidom.parseString(ixml)
    response = doc.getElementsByTagName(tagName)[0].toxml()
    return fromstring(response)
    
class nationalrail:

    # Decorators
    def mandatory(api):
        """
        Decorator to check for mandatory parameters
        """
        def func(*args, **kwargs):
            crs = kwargs.get('crs', None)
            if not crs or len(crs) != 3:
                print "CRS is mandatory for %s call" %api.__name__
                sys.exit(1)
            api(*args, **kwargs)
        return func
        
    def __init__(self):
        """
        Constructor.
        """
        pass
        
    @mandatory
    def departures(self, numRows=5, crs="", filterCrs="", filterType="to", timeOffset=0):
        """
        Method to retrieve the departure details from a station specified by crs.
        @param numRows: Number of rows to be returned
        @param crs: CRS code of the station.
        @param filterCrs: CRS code of an intermediate station to filter the result.
        @param filterType: To indicate if the filterCrs is a from or to station. Default to.
        @param timeOffset: Time offset in 
        """
        result = doSoapCall("GetDepartureBoardRequest", locals()) 
        print result
    
            
def main():
    rail = nationalrail()
    rail.departures(crs="PAD")
        
if __name__ == '__main__':
    main()<commit_msg>Added other api methods.<commit_after>#!/usr/bin/env python
# encoding: utf-8
"""
nationalrail.py

Python implementation for National Rail api (UK).
Author: <NAME>
"""
__VERSION__ = "1.0"

import sys
import httplib, urllib
import xml.dom.minidom
from xml2dict import fromstring

from settings import *
from requests import *

def doSoapCall(soapAction, args):
    """
    Method to make soap call given the url and proper xml.
    Have to do this, since unfortunately all python soap libs sucks.
    Looked at suds, soappy :(
    @param soapAction: Soap Action to use.
    @param host: National rail server host.
    @param url: URL to use for this soap action.
    @param xml: Request xml to be sent to the server.
    """
    hc = httplib.HTTPConnection(HOST)
    xml = SOAPACTION_REQUEST_MAPPING.get(soapAction, None)
    if not xml:
        print "Unable to find the request xml for the action %s" %soapAction
        sys.exit(1)
    xml = xml % args
    headers={
        'Host' : HOST,
        'Accept-Encoding' : 'gzip,deflate',
        'Content-Type' : 'application/soap+xml;charset=UTF-8;',
        'Content-Length' : len(xml),
        'User-Agent' : 'National Rail Enquiries for iPhone 1.2 (iPhone; iPhone OS 3.1.2)',
        'SOAPAction' : '"%s/%s"' %(SOAPACTION_URL_PREFIX, soapAction),
    }
    hc.request ('POST', API_URL, body=xml, headers=headers)
    resp = hc.getresponse()
    data = resp.read()
    if resp.status != 200:
        raise ValueError('Unable to receive expected data : %s, %s' % (resp.status, resp.reason))
    return parseXml(data, soapAction.replace("Request", "Result"))
        
def parseXml(ixml, tagName):
    """
    Method to parse the given xml for the given id and return the result as object
    minidom is used here.
    @param xml: Xml to parse
    @param tagName: Tag name to look for in the xml
    """
    doc = xml.dom.minidom.parseString(ixml)
    response = doc.getElementsByTagName(tagName)[0].toxml()
    return fromstring(response)
    
class nationalrail:

    # Decorators
    def mandatory(api):
        """
        Decorator to check for mandatory parameters
        """
        def func(*args, **kwargs):
            crs = kwargs.get('crs', None)
            if not crs or len(crs) != 3:
                print "CRS is mandatory for %s call" %api.__name__
                sys.exit(1)
            return api(*args, **kwargs)
        return func
        
    def __init__(self):
        """
        Constructor.
        """
        pass
        
    @mandatory
    def departures(self, numRows=5, crs="", filterCrs="", filterType="to", timeOffset=0):
        """
        Method to retrieve the departure details from a station specified by crs.
        @param numRows: Number of rows to be returned
        @param crs: CRS code of the station.
        @param filterCrs: CRS code of an intermediate station to filter the result.
        @param filterType: To indicate if the filterCrs is a from or to station. Default to.
        @param timeOffset: Time offset in 
        """
        return doSoapCall("GetDepartureBoardRequest", locals())

    @mandatory
    def arrivals(self, numRows=5, crs="", filterCrs="", filterType="to", timeOffset=0):
        """
        Method to retrieve the arrival details to a station specified by crs.
        @param numRows: Number of rows to be returned
        @param crs: CRS code of the station.
        @param filterCrs: CRS code of an intermediate station to filter the result.
        @param filterType: To indicate if the filterCrs is a from or to station. Default to.
        @param timeOffset: Time offset in 
        """
        return doSoapCall("GetArrivalBoardRequest", locals())

    @mandatory
    def arrivalsAndDeparture(self, numRows=5, crs="", filterCrs="", filterType="to", timeOffset=0):
        """
        Method to retrieve the arrival and departure details of a station specified by crs.
        @param numRows: Number of rows to be returned
        @param crs: CRS code of the station.
        @param filterCrs: CRS code of an intermediate station to filter the result.
        @param filterType: To indicate if the filterCrs is a from or to station. Default to.
        @param timeOffset: Time offset in 
        """
        return doSoapCall("GetArrivalDepartureBoardRequest", locals())
    
    def serviceDetails(self, serviceID):
        """
        Method to retrieve details about a particular service.
        @param serviceID: Service ID (Identifier representing a train service) obtained from other api.        
        """
        return doSoapCall("GetServiceDetailsRequest", locals())
                
def main():
    rail = nationalrail()
    print rail.departures(crs="PAD", filterCrs="STL")
    print rail.arrivals(crs="HAY")
    print rail.arrivalsAndDeparture(crs="PAD")
        
if __name__ == '__main__':
    main()
{'fraction_non_alphanumeric': 0.10173053152039555, 'fraction_numerical': 0.00519159456118665, 'mean_word_length': 2.5564835164835165, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 40}, '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': '2077961', 'n_tokens_mistral': 2413, 'n_tokens_neox': 2356, 'n_words': 840}