Creating Python reusable functions for REST API and HTML forms

I am building an enterprise app with Python plus Django framework which will expose the data via Forms and also REST API. I am looking to build reusable python functions that will deliver the need for both.

Since I am coming from a Java background, I have tried to code in the same manner in Python but by Python’s way of doing it, however I was surprised to know from that things are bit different in Python.

Here is what I am doing,

Objective: Create a non empty record in the database by receiving the data from

  1. A HTML form
  2. By REST API

So here is how I am getting the form data from custom HTML forms into Django views,


def create_user(request):       userDataModel=UserData()     userDataModel.user_name=request.POST['user_name']     userDataModel.password=request.POST['password']['email']        return create_user_record_redirect(request, userDataModel) 

The above function is in a separate file in Layer 2

from django.db import models    class User(models.Model):     user_name = models.CharField(max_length=100, unique=True)     password = models.CharField(max_length=100)         email = models.CharField(max_length=70) 


Layer 2 is nothing but a separate file that will take the result from the Layer 3 and try to determine whether the record has been successfully been created or not with the help of a dictionary.

def create_user_record_redirect(request, user_record):     obj_response = create_user_record(user_record)     if obj_response.get("Result") == True:         return render(request, "pages/thankyou.html")     else:         return render(request, "pages/page_error.html", {'obj_response': obj_response}) 


This is core place of my application where I will be Creating/Updating/Reading/Updating the records. So anything record that has to be created/deleted/updated will go through these functions.

This will be place where my business logic will reside and will contain all functions needed for the rest of the business modules.

def create_user_record(user_data_model):     ret_obj_dict = dict()      if(user_data_model.user_name not         and user_data_moel.password not         and not):         userdata=User()         user.user_name=user_data_model.user_name         user.password=user_data_model.password          ret_obj_dict['Result'] = True         ret_obj_dict['exception_occured'] = False         ret_obj_dict['exception_message'] = "No Exception"         ret_obj_dict['Message'] = "Record Saved Successfully"         ret_obj_dict['status_code'] = 600     else:         ret_obj_dict['Result'] = False         ret_obj_dict['exception_occured'] = False         ret_obj_dict['exception_message'] = "No Exception"         ret_obj_dict['Message'] = "Missing input Fields"         ret_obj_dict['status_code'] = 550      return ret_obj_dict 

A POJO like class in Python(userDataModel from layer 1)

def UserData():      def __init__(self):         self.user_name         self.password           def user_name(self):             return self.user_name          @user_name.setter         def user_name(self,paramvalue):             self.user_name=paramvalue          def password(self):             return self.password          @password.setter         def password(self,paramvalue):             self.password=paramvalue          def email(self):             return          @email.setter         def email(self,paramvalue):    

So if I am going to create records via the REST API I will just have create an instance of UserData(), set the values and call the function create_user_record and my record would be created.

This was the idea behind this reusing the functions but here are my questions

  1. Does the above slow down the process of saving data ?
  2. Since I am from a Java background and have coded in a similar manner, am I doing in a correct way in Python ?
  3. There is no problem with this or other better solution is available ?

Let me know if any of the above is not understandable and I will gladly re-edit the questions to make things clearer.

Weight functions in graph algorithms

In text books, for instance in the 3rd edition of Introduction to Algorithms, Cormen, on page 625, the weights of the edge set $ E$ is defined with a weight function $ w:E\rightarrow \mathbb{R}$ .

Why is it defined in this way? Why do we need a function? I mean, we all know when working with a graph, that the meaning is just that an edge $ (u,v)$ as a weight $ w$ . So, why is it written with a function? I remember the first time I saw this definition I was very confused. Only after actually going through an algorithm and reading it again, I realized that it really just means that every edge has a its weight.

So, I still don’t fully understand why is it written in this complicated way and what exactly it means though, and it would be very nice if someone could tell me that in a understandable language.

Azure Functions with EF Core Recommended

This is a questions more about if I should more than if I can. I’ve got an existing Azure App Service which started off as a simple rest api that managed communications between mobile apps and multiple instances of an on-premise multi-tenanted ERP system. Probably due to a bit of bad design it’s kind of morphed over recent times to include file hosting, marketing websites and an unrelated web app.

So, my plan is to to pull this api out of the current app service into it’s own to keep maintenance etc a little more streamlined. I was looking at rather than using another App Service, Azure Functions. However, my current api uses a SQL DB (Again hosted in Azure) and EF to store some settings and transactional data.

Now the question is, considering Azure Functions are supposed to be stateless is it considered “Best Practice” to have Functions accessing SQL data via EF (or at all). I’ve seen lots of info telling me how, but no one really seems to say if you should. Or am I just over thinking the “Stateless” thing?

Is bad idea to utilize helper functions on integration tests?

In my job I have a small disagreement on whether we should utilize helper functions for making datasets especially in laravel framework. A sample for the test is:

namespace Tests\MyAppTests;  use PHPUnit\Framework\TestCase; use Carbon\Carbon;  class MyTest extends TestCase {   private function makeATwoHourSpan(Carbon $  now, &$  start, &$  end)   {      $  start = new Carbon($  now);      $  start->modify("-1 hour");       $  end = new Carbon($  now);      $  end->modify("+1 hour");   }    public function testSomething()   {      $  now=Carbon::now();      $  start=null;      $  end=null;       this->makeATwoHourSpan($  now, $  start, $  end);      //Rest Of Test Here   }     public function testSomethingElse()   {      $  now=Carbon::now();      $  start=null;      $  end=null;       this->makeATwoHourSpan($  now, $  start, $  end);      //Rest Of Test Here   } } 

The argument that my supervisor says is that using the makeATwoHourSpan method even though makes the code DRY it does not aid the readability of the test. Also he mentioned that a test should be autonomous and a easy to run as standalone without any helper function except the tools provided from the framework.

So my question is: Should I avoid utilizing “helper” functions especially when I make test data when I make tests, or having a function for data creation makes is the way to go?

Pure functions applied to a two dimensional list

Lets say I have a two dimensional list:

list = {{a, b, c}, {aa, bb, cc}, {x, y, z}, {xx, yy, zz}}; 

and two pure functions:

f1 = Total[#]/Length[#] &; f2 = Total[##]/Length[##] &; 

I want to learn how to apply these functions over rows and columns of a list using Map, MapThread, MapAt and Apply. Here:

f1 /@ list  

produces, as expected,

enter image description here.

But, why MapThread does not work as it supposed to work in MapThread[f1, list]?

Similarly, f1 @@ list works as expected but f1 @@@ list does not work, why?

MapAt[f1, list, 2] works fine but MapAt[f1, list, {All, 2}] does not work, why?

What is the most efficient way to apply these pure functions to columns of the list without Transpose? My goal is to learn how to apply pure functions column wise most efficiently. I would appreciate general answer.

What considerations should I mind when designing methods or functions that take in a lot of parameters?

What considerations should I mind when designing methods or functions that take in a lot of parameters? A lot meaning over 4 but less than 10.

Example, I am debating whether to pass in an array like so:

function makeAssembly(array $  params) {     $  pump = $  factory->fromModelNumber($  params['modelNumber'], $  params['stages'], $  params['x']);             $  motor = $  factory->createMotor($  params['frameId'], $  params['productId'], $  params['x']); } 

versus spelling out parameters in the method header:

function makeAssembly($  modelNumber, $  stages, $  x, $  frameId, $  productId) {     $  pump = $  factory->fromModelNumber($  modelNumber, $  stages, $  x);     $  motor = $  factory->createMotor($  frameId, $  roductId, $  x); } 

Is there a way that is clearly better or are both interchangeable?

In particular, are there any tenants that can be attributed to dependency injection, such as Tell Don’t Ask principles that can be reused in this case as well?

Design pattern for exposing static functions in C/C++ only to unit tests [on hold]

I have some static free functions (the don’t belong to a class) in a C++ file. I want them to still be only visible within such module and to be free, but I want to test them with unit tests as well.

As far as I can see, the are several possible options:

  • Using macros, enable/disable the static keyword depending on whether or not a variable (TEST_MODE) is defined or not:
#ifdef TEST_MODE    #define static #endif 
  • Use ‘private headers’: create a header file whose name ends with _private and whose location is in include/private.

  • Declare the functions in the normal header file adding like a private section with code comments. Like /////// PRIVATE SECTION ///////

  • Include the *.cpp file in which they are declared (personally I don’t like this option at all)

  • Group the private functions in a ‘private’ namespace. Like namespace myNamespace { namespace private { .... } }. The problem with this one is that it can’t be used in plain C.

  • Use compiler directives for hiding stuff, like __attribute__(("hidden"))

I would say that my favourite one is the private header, it seems to be clean and does not need namespaces, in case the language doesn’t support them.

Which one is considered the best practice?