Java's "UserContext" equivalent in Django - django

I'm writing REST services using Django Rest Framework. I want to keep some of the values like Language Code, AppId in a global variable (not static) and access it where ever I want. This may change for every request. In Java we call it as "UserContext". So that I can parse my header and assign the values into that and access it in Data or View Layer (for example). This will help me to avoid passing the values in every method. At the same it has to maintain life cycle for each request.
Is there anything like that in Django?

The plain answer is that django-tls (https://github.com/aino/django-tls) can make request available everywhere where you import it, and then you can just set attributes on request, request.user, or something similar.
That said, in 99% of the cases this is a bad idea, for instance if all you need it for is to avoid passing values to functions then it's extremely ill advised. You'll just make your code unreadable. If you have a lot of variables to pass around, maybe some of them need combining into some class?

Related

Is there a way to create a constrained data type in Clojure?

As an example, a string that contains only a valid email address, as defined by some regex.
If a field of this type would be a part of a more complex data structure, or would be used as a function parameter, or used in any other context, the client code would be able to assume the field is a string containing a valid email address. Thus, no checks like "valid?" should be ever necessary, so approach of domaintypes would not work.
In Haskell this could be accomplished by a smart constructor (section 1.2) and in Java by ensuring the type is immutable (all setters private) and by adding a check in the constructor that throws a RuntimeException if the string used to create the type doesn't contain a valid email address.
If this is impossible in plain Clojure, I would like to see an example implementation in some well known extensions of the language, like Typed Clojure.
Ok, maybe, I understand now a question and I formulate in the comment my thoughts not really well. So I try to suggest an admissible solution to your question and then I try to explain some ideas I tried to tell in the comment.
1) There is a gen-class that generates compiled bytecode for a class and you can set constructor for the class there.
2) You can create a record with defrecord in some namespace that is private by convention in your project, then you
create another namespace with public api and define your factory function here. So the user of your public namespace will be able to call only public functions of your public namespace. (Of course, he can call also private ones, but with some another code)
3) You can just define a function like make-email that will return a map.
So you didn't specify your data structure anywhere.
4) You can just document your code where you will warn people to use the factory function for construction.
But! In Java if your code requires some interface, then it's user problem to give to your code the valid interface implementation. So if you write even a little bit general code in Java you already has lost the property of the valid email string. This stuff with interfaces is because Java is statically typed language.
Clojure is, in general, dynamically typed, so the user, in general, should be able to pass arbitrary data structure to arbitrary function without any type problems in compile time and it's his fault if he pass the wrong data. That makes, for example, this thing possible: You create a record and create a factory (constructor) function. And you expect a record to be passed in your code. But the user can pass a map with the same keys as your record fields names and the code will work.
So, in general, if you want the user of your code to be responsible for passing a required typed in dynamically typed language, then it cost nothing for user to be responsible for constructing it in a correct way that you provide to him.
Another solutions are: User just write tests. You can specify in your api functions :pre and :post conditions to check the structure. You can use typed clojure with the ideas I wrote above. And you can use some additional declarative libraries, like that was mentioned in the first comment of #Thumbnail.
P.S. I'm not a clojure professional, so I could easily miss some better solutions.

Famo.us: different ways of creating and calling functions

Hoping someone can provide an explain-like-I’m-five elucidation of the difference between the following types of functions within Famo.us, and when it’s appropriate to use them:
sampleFunction() {}
_sampleFunction() {}
SampleView.prototype.sampleFunction() {}
.bind and .call are also thrown around a lot…I understand them vaguely but not as concretely as I’d like. That might be a different question, but please feel free to use them in your explanation!
Apologies for the vagueness...wish there was more regarding this in famo.us university.
None of what you're looking at is syntax specific to Famo.us. It's actually common, if intermediate level, VanillaJS.
The _ is simply a coding convention to denote that a specific function should belong to the parent scope (ie a member/private function, whatever you prefer to call it). Javascript doesn't really have support for encapsulation - the act of blocking other classes and objects from accessing another class's functions and variables. While it is possible, it's quite cumbersome and hacky.
You'll see that Famo.us uses the underscore convention to denote that a function is a member of the class using it. Some of these functions are actually just aliases to the actual Javascript native function, for example ._add actually just call's Javascript's .add method. Of course, ._add could be updated in the future on Famo.us's end to do more in the future if that's required. You really wouldn't want to try and write over the native Javascript add. That's super bad.
The other upshot is that you can document that class and say that you can and should use the _add method for a specific purpose/scenario. You'll see that in the API docs.
Understanding prototype is a core part of what it means to be a Javascript Programmer, after all, it is a prototype driven language. MDN has a much better explanation than anything I can offer here but it's basically at the core of your classes.
If you want to extend off of an existing class (say, create your own View or Surface type) you would extend it's prototype. Check out Famous Starter Kit's App examples and see how many of them create an "AppView" class, which takes the prototype of the core View, copies it for itself, and then adds it's own functions, thus extending View without ruining the original copy.

Advice for refactoring cfmodule into... cfc's?

I have never wrote a line of cfmodule myself. However, now is the time to refactor. What steps do you usually take to refactor cfmodule into cffunction / .cfc?
I'm thinking... refactor them into cffunctions (attributes becomes arguments), and return struct for multiple values, value for single value. Then group related functions into CFC's, and separate DB access into DAO/Gateway object. Unit test the hell of each of them.
Alternative, my colleague is thinking, maybe we should use a CFC for each 'flow' of cfmodules, and use obj's variables.instance scope as caller scope, then return the instance struct at the end of the 'flow'? Easier, but doesn't seem very testable.
Anyone has exp with refactoring cfmodule's?
Refactor your objects into CFC's as you're thinking.
Refactoring the application into divisions based off of the current procedural use is the wrong approach for sure. You basically hard coding your business logic to your value objects, which is a no no.
When it's time to add functionality with your existing codebase, you'll be glad you didn't group your logic in with your data. :)

What is the preferred Restful URI design to distinguish between a collection and singleton resource?

I have a URI structure which is hierarchical for a particular data set:
/Blackboard/Requirement/{reqID}/Risk/{riskId}/MitigationPlan/{planId}
If the url is split at various IDs you can get that particular resource e.g.:
GET: /Blackboard/Requirement/2/Risk/2
This gets Risk #2 associated with Requirement #2
The question is this: a desired feature is now to be able to update (PUT) and delete (DELETE) a set of requirements in the same HTTP request. (The entire 'set' of requirements is GET-able when you fire an HTTP GET to the /Blackboard URL - that's the default functionality since something is written on the blackboard, figuratively)
So should I create a new collection resource URL only supporting PUT/DELETE like this:
/Blackboard/Requirements : HTTP PUT/DELETE
(note the plural)
or actually make the existing URL structure plural
/Blackboard/Requirements/{reqID}/Risk/{riskId}/MitigationPlan/{planId}
The latter seems to break semantic uniformity since the other items in the hierarchy are singular. Should I make them plural too??
Does having an item id help disambiguate singularity (from a human perspective :) like Blackboard/Requirements/1 or is it preferable to expose a different resource (i.e., a collection) purely for operational reasons (since GET is not allowed without id - irrespective of it being singular or plural)?
Just wanted to know the opinions of the community on which approach is commonly chosen (or is the right way of doing it) for clarity cleaner design.
The latter seems to break semantic uniformity since the other items in the hierarchy are singular. Should I make them plural too?
You should want your url's to be cool. So if you do change them to make it match, make sure your old singular urls return redirects with the new locations. Determining the expensive of that might help make the decision of change/no-change. If your API isn't used yet, then there's no barrier one way or the other. IMO, I'd go for consistency.
Does having an item id help disambiguate singularity (from a human perspective :) like Blackboard/Requirements/1 or is it preferable to expose a different resource (i.e., a collection) purely for operational reasons (since GET is not allowed without id - irrespective of it being singular or plural)?
For me, it makes more sense to have the url collections plural even with id. That could be a bias from file systems though. In that sense, it only makes sense that a single resource would be deeper in the url than the collection resource. It also give an easy way back to the collection resource, a url breadcrumb.

Consuming custom objects between webservices

I have a webservice that is designed to accept performance data via a custom object. The custom object contains a Collection (Generic List) of performance measures among other data. The performance measure consists of simple data types (strings, ints, and a datetime). The only method exposed by the webservice requires this custom object (performance data object) to be passed in.
The problem lies in using this custom object externally. I wish to use the Add() and Item() methods of the Generic List class along with various other features within this class within another webservice. If I request the object from the Performance Data Webservice it seralizes the inner collection to an arrayList. I would like it to remain a generic collection.
I have toyed with using the XmlInclude method but currently havent found a solution with it.
The next thing I tried to do was create an assembly of this specific object that both the Peformance Data web service can use and any satelite programs (i.e. another webservice). The issue here is when I try to pass in the custom object created by the seperate assembly the performance data webservice barks its a different type. (Also I am applying the XmlInclude(GetType( custom assembly)) attribute to the exposed method). However still thinks the types are not convertable.
Note: I would prefer to call the Performance Data WS to get the custom object instead of having to deal with adding assemblies to each project that needs access.
Anyone have an idea other than restructing the program to work with methods exposed by the ArrayList?
If you use WCF, you can configure what type of collection comes out, whether an ArrayList, a fixed array, or a generic List.
I have found a solution that will work with .Net 2.0. By using Web Services Contract First (WSCF http://www.thinktecture.com/resourcearchive/tools-and-software/wscf/wscf-walkthrough)
I was able to pass generic collections between two services. A down side to WSCF, as the name suggests, is the approach requires the use of contract-first instead of the more common code-first methodology. Lucky it is not terribly complicated to modify the class and proxy after they are created. Hope this helps any lost travelers...