How to derive the binomial test? From what I understand from a pervious question I asked, the p-value for a particular binomial test (specifying a number of flips, and number of heads and tails, and a null-hypothesis to test against) loosely describes the probability that this data is expected with the assumption that the null-hypothesis is correct.
So if I do a binomial test for binom_test(numberOfHeads=9, numberOfFlips=10, weight = .5), and obtain a pvalue for the 2-tailed test. This represents the probability that such an event (nine heads in 10 flips) could occur by a fair coin. If this number is very small, then we can assume that the null hypothesis is rejected with some level of statistical confidence.
My issue is that I'm having a lot of trouble understanding what the derivation of the binomial test. In python there is a binomial test function, but they simply link to the wikipedia article on binomial test.
Intuitively if my null hypothesis is p=1/2, shouldn't my binomial test just be the binomial distribution? For example, I would have thought that my pvalue getting 4 heads in 5 flips would be just the probability of a fair coin getting 4-heads in five flips. So  ${5 \choose 4} (1/2)^4(1/2)^5$. Is this correct? I am looking at what is done on wikipedia and it doesn't seem as though it's in agreement with my thoughts - but what they have written (particularly for the two tailed test) is very unclear to me.

There are already some very good answers here, but I figured I would offer my own take.
You're correct in identifying the interpretation of the p value of the test:  The probability of seeing 9 or more heads from a fair coin assuming all other assumptions are correct.
Note that the binomial test is in terms of the coin's bias, not in terms of the number of heads as you might expect for the binomial distribution.  But, I can always obtain the number of heads by multiplying by the number of flips made since $\widehat{p} = x/n$, where $p$ is the estimated bias, $x$ is the observed number of heads, and $n$ is the number of flips.
Because $n\widehat{p}$ is an estimate of the expectation of the number of heads, it has some desirable properties.  Due to the central limit theorem, we know
$$ n\widehat{p} \sim \operatorname{Normal}\big(np_0, np(1-p_0)\big) $$
where $p_0$ is the true bias. This implies
$$ \dfrac{\widehat{p} - p_0}{\sqrt{\dfrac{\widehat{p}(1-\widehat{p})}{n}}}\sim \operatorname{Normal}\big(0, 1\big) $$
Here, I've replaced $p_0$ with $\widehat{p}$ in the expression for the variance so align with the common Wald test statistic.  Keeping $p_0$ in the variance expression would result in a Score test.
This is the test statistic for the binomial test.  Our test statistic is based off a normal approximation to the binomial distribution, which becomes better when $n \to \infty$.
