I have written this piece of code:
@staticmethod
def __ver_upload_url(document_type, document_subtype=None):
verification_base = 'verification/{0}/'.format(document_type)
verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''
I was wondering if there was a cleaner, more Pythonic way of formatting the URL path in just one line. I initially had:
verification_base = 'verification/{0}/{1}'.format(document_type, document_subtype) \
if document_subtype is not None else 'verification/{0}/'.format(document_type)
I think it is cleaner and more readable now, but maybe there is still a better way.
Note: I am trying to generate a path for a Django file that must be uploaded, and files have always types, but not always subtypes (as in categories and subcategories). I want to add a subdirectory to specify the subtype only if the file has a subtype, and if not leave it inside the folder named as the type.
I had to escalate my function and now it looks something like:
def verification_url(document_type, document_subtype=None, company=False, company_administrator=False):
verification_base = 'verification/'
verification_base += 'companies/' if company or company_administrator else ''
verification_base += 'admins/' if company_administrator else ''
verification_base += '{0}/'.format(document_type)
verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''
def function(instance, filename):
id = instance.id if company else instance.user.id
return verification_base + '{user_id}/{filename}'.format(id=id, filename=filename)
I was wondering that maybe I could write a URL builder that depends upon a list of elements that will be inserted into a string limited by slashes, to reduce the length of my code, or make it reusable at least.
What are your suggestions to improve the efficiency / scalability of the code?
The regularity of the tokens you are combining suggests a join
-based approach:
bits = ('verification', 'companies', 'admins', document_type, document_subtype)
flags = (1, company or company_administrator, company_administrator, document_type, document_subtype)
verification_base = '/'.join([b for b, f in zip(bits, flags) if f]) + '/'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.