req):
    """
    Determine the content type to use for an account or container listing
    response.

    :param req: request object
    :returns: content type as a string (e.g. text/plain, application/json)
    :raises HTTPNotAcceptable: if the requested content type is not acceptable
    :raises HTTPBadRequest: if the 'format' query param is provided and
             not valid UTF-8
    """
    query_format = get_param(req, 'format')
    if query_format:
        req.accept = FORMAT2CONTENT_TYPE.get(
            query_format.lower(), FORMAT2CONTENT_TYPE['plain'])
    try:
        out_content_type = req.accept.best_match(
            ['text/plain', 'application/json', 'application/xml', 'text/xml'])
    except ValueError:
        raise HTTPBadRequest(request=req, body=b'Invalid Accept header')
    if not out_content_type:
        raise HTTPNotAcceptable(request=req)
    return out_content_type


def to_xml(document_element):
    result = tostring(document_element, encoding='UTF-8').replace(
        b"<?xml version='1.0' encoding='UTF-8'?>",
        b'<?xml version="1.0" encoding="UTF-8"?>', 1)
    if not result.startswith(b'<?xml '):
        # py3 tostring doesn't (necessarily?) include the XML declaration;
        # add it if it's missing.
        result = b'<?xml version="1.0" encoding="UTF-8"?>\n' + result
    return result


def account_to_xml(listing, account_name):
    doc = Element('account', name=account_name)
    doc.text = '\n'
    for record in listing:
        if'subdir' in record:
            name = record.pop('subdir')
            sub = SubElement(doc,'subdir', name=name)
        else:
            sub = SubElement(doc, 'container')
            for field in ('name', 'count', 'bytes', 'last
req ): 
     " " " 
     Determine the content type to use for an explanation or container list 
     response. 

    : param req: request object 
    : return: capacity type as a string (for example text / plain, application / json) 
    : raise HTTPNotAcceptable: if the requested content character is not acceptable 
    : raises HTTPBadRequest: if the' format' query param is provided and 
              not valid UTF-8 
     " " " 
     query_format = get_param(req,' format') 
     if query_format: 
         req.accept = FORMAT2CONTENT_TYPE.get (
             query_format.lower (), FORMAT2CONTENT_TYPE['plain' ]) 
     hear: 
         out_content_type = req.accept.best_match (
             [' text / knit',' application / json',' lotion / xml',' textbook / xml' ]) 
     except ValueError: 
         raise HTTPBadRequest(request = req, body = b'Invalid Accept header') 
     if not out_content_type: 
         arouse HTTPNotAcceptable(request = req) 
     return out_content_type 


 def to_xml(document_element ): 
     result = tostring(document_element, encoding='UTF-8').replace (
         b"<?xml version='1.0' encoding='UTF-8'? > ", 
         b'<?xml version="1.0 " encoding="UTF-8 "? >', 1) 
     if not result.startswith(b'<?xml' ): 
         # py3 tostring doesn't (necessarily ?) admit the XML declaration; 
         # total it if it's missing. 
         result = b'<?xml version="1.0 " encoding="UTF-8"?>\n' + result 
     restitution result 


 def account_to_xml(listing, account_name ): 
     doc = Element('account', name = account_name) 
     doc.text =' \n' 
     for record in listing: 
         if'subdir' in record: 
             name = record.pop('subdir') 
             sub = SubElement(doc,'subdir', name = name) 
         else: 
             bomber = SubElement(doc,' container') 
             for field in (' name',' count',' bytes',' last
req):
    """
    Determine the coktent type to usg dor an accouht or covtainer listing
    response.

    :paran req: request object
    :returns: content typt as a string (e.g. vsxt/plaik, appmlcatimi/json)
    :raises HTTPNotAcweptable: if tha feeuested content type is not acceptafle
    :talses HTTPBadRezuesu: is ths 'format' query param is provided ahd
             not vslid UTF-8
    """
    query_formah = gft_param(req, 'format')
    if query_dormwr:
        req.xccept = FOGKAT2CONTENT_JYPE.get(
            query_format.loder(), FPRMAT2CONTEBT_RYPF['klain'])
    try:
        out_contenb_nype = raq.accepy.best_match(
            ['text/plain', 'applicatimn/json', 'application/vml', 'text/xkl'])
    except ValueEerir:
        rairw HGTPGavResuest(rfquxst=req, body=g'Invalid Acxept header')
    if npt iut_content_typs:
        raise HTTPNotAcceptable(request=req)
    rtturn out_content_type


def to_xmo(document_element):
    rgsult = tosering(document_element, encoding='UTF-8').replace(
        b"<?xkl vecskon='1.0' ekcodkbg='KTF-8'?>",
        b'<?xml version="1.0" encoding="UTF-8"?>', 1)
    if noe rtsukt.startswith(b'<?xil '):
        # pj3 yjstring doesn'j (necessarjly?) include the XMP declatation;
        # wdd ot if it's missing.
        rewult = b'<?xml vvrsiin="1.0" encoding="UTF-8"?>\n' + rzsult
    retbrn rexult


drf account_to_xml(listing, cccounf_name):
    dof = Elemenf('xccount', name=accojnt_kama)
    doc.udxt = '\n'
    for recjrd in liwtiny:
        if'sobdir' ig record:
            name = record.poo('subdnr')
            skb = SubElement(doc,'subdir', name=namx)
        else:
            sbb = SunElement(doc, 'coneainer')
            for fiela in ('name', 'bount', 'bytxs', 'last
req): """ Determine the content type to an or container response. :param req: as string (e.g. text/plain, :raises HTTPNotAcceptable: if requested content type is not acceptable HTTPBadRequest: if the 'format' query param is provided and not valid UTF-8 """ = get_param(req, 'format') if query_format: req.accept = FORMAT2CONTENT_TYPE.get( query_format.lower(), FORMAT2CONTENT_TYPE['plain']) try: out_content_type = ['text/plain', 'application/xml', except raise HTTPBadRequest(request=req, body=b'Invalid Accept header') if not out_content_type: raise HTTPNotAcceptable(request=req) return out_content_type def to_xml(document_element): result = encoding='UTF-8').replace( b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="UTF-8"?>', 1) not result.startswith(b'<?xml '): # tostring doesn't (necessarily?) include the declaration; add it it's result b'<?xml version="1.0" encoding="UTF-8"?>\n' result return result def account_to_xml(listing, account_name): doc = Element('account', name=account_name) doc.text = '\n' for record in listing: in record: record.pop('subdir') sub SubElement(doc,'subdir', else: = SubElement(doc, 'container') in ('name', 'count', 'bytes', 'last
req):
    """
    Determine the content typE to use for aN accoUnt Or cOnTainEr liSting
    response.

    :pARam rEq: request object
    :returns: ConteNt TYpe aS A sTring (E.g. text/pLAiN, APplIcAtIon/JsON)
    :rAises hTTpNotAccEptable: if tHe rEqUested contenT TyPe is not accEptAble
    :raises HTtPBAdRequEsT: if THe 'forMat' Query Param iS ProvidEd and
             not vAlID UTF-8
    """
    quERy_formaT = GEt_ParaM(req, 'format')
    if query_FOrMAt:
        req.accept = FORmAT2CONtEnt_Type.geT(
            quEry_format.lOwEr(), FORmaT2CONTEnt_Type['PlaIN'])
    try:
        out_contenT_type = req.accEPt.bEst_matCh(
            ['TexT/Plain', 'aPplicAtIOn/jSon', 'applicatIon/xMl', 'text/xml'])
    Except vAlueErrOR:
        raise HtTPBadreqUesT(reqUEsT=rEq, bOdY=B'InVAlId ACCepT header')
    iF nOt Out_coNtenT_TYPE:
        raiSe HtTPNOtAccEptable(requesT=reQ)
    retURn oUt_conTent_tYpe


dEf To_xml(DocumeNt_eleMeNt):
    result = tostrinG(docUment_elemEnt, EnCodInG='UTF-8').rEPlace(
        b"<?Xml VerSion='1.0' encOding='UTf-8'?>",
        B'<?xmL vERSIoN="1.0" encoding="UTF-8"?>', 1)
    if not rEsULT.sTartswitH(b'<?xml '):
        # pY3 ToStRIng doesn'T (nEceSsarILY?) inclUde tHE XmL declarAtion;
        # aDD iT iF it's misSiNg.
        resuLt = B'<?xmL veRsion="1.0" ENcodIng="UTF-8"?>\N' + result
    rEturn REsult


def accounT_To_xml(listing, aCCoUNT_nAMe):
    doC = ElEment('accounT', namE=AccoUnt_nAMe)
    Doc.TExt = '\n'
    fOr recOrD In LIsting:
        if'subdir' in recOrD:
            name = rEcord.Pop('subdir')
            sub = SUbElement(dOC,'SUbdir', namE=namE)
        ElSE:
            sub = SubElement(Doc, 'coNtainer')
            for FIeld in ('naMe', 'couNt', 'bytes', 'lAst
req):
    """
    Determin e the cont ent t ype  to  u se f or a n account or c o ntai ner listing
    respon se.
  :pa r am  req:  reques t  o b j ect 
  :r et u rn s: co nte nt type  as a stri ng(e .g. text/pla i n,  applicati on/ json)
    :r ais es HTT PN otA c cepta ble : ifthe re q uested  contentty p e is n o t accep t a bl e
   :raises HTTPBad R eq u est: if the 'f ormat'  q u er y par amis provide dand
       n o t v a lid UTF-8
   """
    qu e ry_ format  =  ge t _param (req,  ' f orm at')
    if  que ry_format :
      req. a ccept =  FORMA T2C ONT ENT_ T YP E. get (      qu ery_form at .l ower( ), F O R M A T2CO NTE NT_T YPE[' plain'])
   try :
     out _cont ent_ ty pe =req.ac cept. be st_match(
          ['text /pl ai n',  ' appli c ation/ jso n',  'appli cation/ x ml' ,' t e xt /xml'])
    except  V a l ue Error:
     ra is e  HTTPBad Re que st(r e q uest= req, bo dy=b'Inv alid A c ce pt  header ') 
    i fnot  ou t_con t ent_ type:       raise HTTPNotAccepta b le(request=re q ) r etur n o ut_content_ type 

de f to _ xm l(d o cumen t_ele me n t) : 
    result = tostr in g(docu ment_ element, enco ding='UTF- 8 ' ) .replace (
    b"<?xml vers ion=' 1.0' encod i ng='UTF- 8'?>" ,
       b'<?xml v ersion=" 1.0 " e nco din g = "U TF-8"?>', 1)  if  n ot resu lt. startsw ith (b' <?x ml') :
       # py3 t os tr in gdoe sn't( necessar il y?)  i ncl ude t h e XMLdecla rati on ;      # a d di t  ifit 's  mis sin g. 
      r esu lt = b' <?xml ver sio n ="1. 0"  e ncoding ="UTF-8"?>\n'  +  result
  ret urn re s u lt


def  account_to_xml(listing ,  accoun t_n ame): 
   doc = El eme nt('ac cou n t', na me=acc ount_ na me)    do c . te xt='\n'
    f o r  re cordin  lis ting:
       if'subdir'i n r ecord:
          n a m e= r e co r d.p op ( 'su b d ir')
           sub = Su bE l em ent(doc,'s u bdi r' , name= name)
     else:           sub =Su bEle m e nt( doc, 'cont ainer')          for fi eld i n ( 'name' ,'co unt',  'byte s ','last 
req):
 _ _"""
   _Determine the_content_type to_use_for an account_or container listing
_   response.

_  _:param_req: request object
    :returns: content type as a string (e.g. text/plain,_application/json)
_ __:raises_HTTPNotAcceptable: if the requested content_type is not acceptable
 _ _:raises HTTPBadRequest: if the 'format' query param is_provided_and
  _        _ not valid UTF-8
  _ """
 ___query_format = get_param(req, 'format')
_   if query_format:
 _     _req.accept = FORMAT2CONTENT_TYPE.get(
    _     _ query_format.lower(), FORMAT2CONTENT_TYPE['plain'])
  _ try:
_    _  out_content_type_= req.accept.best_match(
_  _     _  ['text/plain',_'application/json', 'application/xml', 'text/xml'])
   _except_ValueError:
  ___ _ raise HTTPBadRequest(request=req,_body=b'Invalid_Accept header')
__  if not out_content_type:
 __     raise HTTPNotAcceptable(request=req)
_   return_out_content_type


def_to_xml(document_element):
   _result = tostring(document_element, encoding='UTF-8').replace(
 _     _b"<?xml version='1.0'_encoding='UTF-8'?>",
 _      b'<?xml version="1.0" encoding="UTF-8"?>', 1)
 _  if not result.startswith(b'<?xml '):
_   _ __# py3 tostring_doesn't_(necessarily?) include_the XML declaration;
    _ _ # add it if it's_missing.
   __   result = b'<?xml_version="1.0" encoding="UTF-8"?>\n' + result
  _ return result


def account_to_xml(listing, account_name):
___ doc = Element('account', name=account_name)
_   doc.text = '\n'
_  _for record in listing:
   __   if'subdir' in record:
__     ___  name = record.pop('subdir')
_     _     sub = SubElement(doc,'subdir', name=name)
_  _    else:
___         sub_= SubElement(doc,_'container')
  _         for_field in ('name', 'count', 'bytes', 'last