Considering they fought with the Axis, and all other Axis allies in Europe were turned into Soviet puppet states, how did a country which borders the USSR avoid a similar situation?
The short answer is that the Finnish army fought well enough that the Soviet leadership realised that they needed the forces fighting Finland against the Germans more than they needed a subjugated Finland.
The long answer is a bit longer.
After the Winter War, the Germans actively courted the Finns as a potential ally against the Soviet Union, something which they stepped up after their victory on the Western Front May-July 1940. The Germans sold arms (much of it war booty from France and Poland) at discount prices to the Finns, who added them to the extensive (but often obselete) shipments they had recieved during and immediately after the Winter War. The Germans also guaranteed Finland deliveries of grain, fertilizer and other needed resources.
As the Soviets during this time were provoking the Finns and actively sought German support to "resolve the Finnish issue" (as they had in 1939), the Finns felt alone and threatened. When the proposed Swedo-Finnish state union fell apart in late 1940, the Finns turned to the Germans, who were happy to help, and soon German troops were stationed in Finland and actively worked on defensive installations around Petsamo, where the Finns had nickel mines the Germans were more or less dependent on for their nickel supplies.
The Finns joined the Germans as co-belligrent in July 1941, but never signed into the Axis. They allowed the German 20. Gebirgsarmee to operate from Finnish territory against Murmansk and to be supplied over Finnish ports, roads and railroads.
The Finns mobilised a re-trained and re-equipped army experienced from the Winter War and launched an offensive during Summer 1941, capturing substantial territory in Far Karelia, but eventually failing to sever the Murmansk railroad. Some sources indicate that British and US warnings against doing so would mean no Western Allied support for Finnish independence after the war made the Finns cease offensive operations, others indicate that the III. Corps (with the reinforcement of the SS Division 'Nord') proved incapable of penetrating the Soviet defences.
As Autumn aproached, the Finns dug in and demobilised parts of their army as manpower was needed in agriculture and industry. The Soviets attempted a counter-offensive late winter/early Spring 1942, but the Finns held their lines. After this, the Finnish front turned into a stalemate from the White Sea to the Baltic Sea.
Until the Soviets launched a large offensive in Summer 1944.
The Leningrad front massed 260 000 troops, 7 500 artillery pieces and about 630 tanks and assault guns for an offensive to crush the Finnish army and knock Finland out of the war. Normally, the Finnish radio interception department and long range patrol recoinnasance behind enemy lines were capable of detecting movement of Soviet large units, but the Soviets planned the movement of the 21. Army to the Leningrad front very carefully and managed to move it to the front without the Finns detecting it. General Lennart Oesch wrote afterwards that the Soviets managed to hide their concentration of troops and equipment 'suprisingly well'. The Soviets had also used air recoinnasance extensively and supplied officers and NCOs down to platoon commanders with detailed photos of the field fortifications of the Finnish lines. They also prepared a massive pre-calculated artillery barrage of the Finnish line.
On the morning of the 9th of June 1944, the Soviet air force attacked the front positions of the Finnish 2. and 10. Division on the Karelian Isthmus for an hour, after which a 10 hour artillery barrage commenced. At the same time, SOviet bombers attacked reserves, communications hubs, railroad stations and lines and artillery positions behind the Finnish lines.
The Finnish main defesnive line was breached and the Finns retreated to their secondary line, the so-called VT-line.
The Finnish defensive lines on the Karelian Isthmus.
However, on the 14th of June, despite the Finns rushing reinforcements to the front, the VT-line was penetrated, and an attempt by the Finnish Armoured Division to counter-attack failed, with heavy casualties for the motorised Jäger infantry of the Armoured Division. The Finnish forces withdrew to the VKT-line.
At this time, the Finns desperately sought help from the Germans, who were reluctant to give any. During 1943, the Finns had sent out feelers for a separate peace with the Soviets, negotiations which had stranded in March 1944. The Finnish Chief of Staff, General Heinrichs requested 6 German divisions. The Germans demanded that the Finnish ally with Germany and leave guarantees they would not seek a separate peace. On the 26th of June PResident Ryti personally promised the German foreign ministet that he would not seek peace with the Soviets.
On the 20th of June Viborg/Viipuri fell and thus the VKT-line was breached - the Finnish 20. Brigade, newly raised, routed and fled in panic instead of defending the city.
The Germans then delivered Panzerfaust and Panzerschreck infantry anti-tank weapons and transported the 303. StuG brigade and the 122. Infanterie-division to help hold the SOviets off. They also shipped 20 Pz IVH tanks, but they arrived too late to take part in the battle. The German ground forces would mostly take up positions on the western side of the Bay of Viborg/Viipuri to prevent the Soviet landing attempts by crossing in small motor boats and thus freeing the Finnish forces for the decisive battle that was coming up - Tali-Ihantala. The German air unit 'Kuhlmey' named after its commander, a mixed unit of Fw 190 fighters and figher-bombers and Ju 87 dive bombers proved a great help, both in attacking Soviet columns and in contesting the air space over the battlefield with the Soviet air force. The Soviets had also outrun their heavy artillery support and had problems moving the guns forwards due to bad infrastructure and a shortage of prime movers for heavy artillery. Thier artillery system and doctrine, which was well suited for pre-planned barrages and creeping fire was not suited for mobile combat (which is why they developed so many successful assault guns - to provide troops with direct artillery support that could move with them).
By this time, the Finns had mobilised more forces and moved 2 divisions from the front north of Lake Ladoga to counter the Soviet offensive. The Aunus Group north of Lake LAdoga was also under attack and retreated back to the original border. The Soviet radio discipline had broken down, and the Finnish radio interception could hear Soviet artillery observers giving instructions to artillery crews in uncoded clear language and commands being issued. During 1942-43, the Finnish General Nenonen had developed a new doctrine for the Finnish artillery, which included pre-calculated artillery data with so-called fire correction circles to rapidly correct fire and decentralised artillery command as well as rapid fire on one target by multiple batteries (since the first shells are the most effective, since troops under fire will seek protection or leave the area under fire after the first few shells). This doctrine and system allowed the Finns to direct as many as 250 guns towards the same target at the same time, and they made excellent usage of this during the battle. Several times the Soviet attacks were broken up as they were massing in front of the Finnish lines.
For example, on the 2nd of July, the Finnish intercepted radioed orders for the SOviet 63. Rifle Division and 30. Armoured Brigade to mass for an attack. 30 Finnish and 30 German bombers attacked the zone of concentration, and 250 guns fired 4 000 shells into the area, making the Soviet attack weak enough that by that evening the Finnish forces had restored their lines by counterattacks.
On the 9th of July, it was evident that the Soviets had spent most of their offensive capacity and that the Finnish army was not broken. At the same time Operation Bagration, the grand Soviet summer offensive against the German Army Group Centre was well under way and successful enough. The Soviets started moving their best troops, heavy artillery, tanks and assault guns away from the front. At the same time, the Soviets let the Finns know that they were no longer demanding unconditional surrender. President Ryti resigned, allowing Mannerheim to become President and thus circumventing his personal promise to not initiate peace negotiations and Finland could make peace without being occupied and becoming a Soviet client state, mostly due to the performance of the Finnish army on the battlefield, but also due to the Soviets having bigger fish to fry in the form of the German troops still deep in the Soviet Union.
Sources:
Liten kugge i stort spel (small cog in a big game) by Leo Wikman.
Ett land i kamp (A nation in struggle), collection of Swedish-speaking Finnish veterans published by Svenska Folkskolans vänner (Swedish school's friends).
Svenskarna vid Jandeba (the Swedes at Jandeba) by Nicolas von Schmidt-Laussitz.
Strider i Fjärrkarelen (Fighting in Far Karelia) by Jukka L Mäkelä.
Oavgjort i två krig (A draw in two wars) by Harry Järv.
Karelska Näset 1944 (Karelian Isthmus 1944) by Ilja Mosjtjanski.
Med döden i hälarna (With death on their heels) by Erik Appel.
Sourced article on Finnish artillery doctrine - http://www.winterwar.com/forces/FinArmy/FINartiller.htm#VPNenonen - by Sami H. E. Korhonen.
EDIT: Had to cease writing for the night, failed to notice /u/vonadler had already produced a very nice answer. Oh well, here goes anyway :).
By a combination of being unimportant enough for grand strategy, stopping the Red Army on its tracks and being in general so stubborn that occupation would've been costly, while being useful enough for the Soviets even without Communist government.
It's probably best to start from about 1942-43, when Finland had re-entered the war in an attempt to take back what she had lost in the Peace of Moscow in 1940. Even though there certainly were those who were sure that the German arms would deliver their dream of destroying the hated Soviet aggressor and usher in the "Greater Finland," the Finnish political leadership and military high command were far more realistic and understood that they would almost certainly have to be neighbours with Soviet Union even after the war. The Finnish objective in the Continuation War (1941-44) was to secure relatively easily defensible borders - the watchword was "short borders - long peace" - with a bit of extra that was to be used as a bargaining chip in the post-war settlement. Most Finns were fairly suspicious of Nazi Germany as well, and the most desirable endgame for them was a victory by the Western allies while Germany and Soviet Union destroyed each other. Therefore, by early 1942, Finnish forces had stopped their advance and essentially dug in for the remainder of the war, refusing German entreaties to cut the Murmansk railway or choke Leningrad.
By early 1943, Finnish leadership was fairly sure that Germany was going to lose the war. Most had accepted this as a fact as soon as the United States entered the war, and remaining doubts were dispelled after Stalingrad. As a result, Finland began fairly early to send out peace feelers. A contact with the Soviets was established in early 1944, but the Soviet demands amounted to unconditional surrender, almost certainly followed by an occupation (if for no other reason, to expel German troops from Northern Finland). Negotiations were cut off, and Stalin ordered Finland to be subjugated by force.
The red hammer struck on 9th June, just three days after D-Day landings in Normandy. An artillery and aerial bombardment on a scale the world had never seen before, and that would only be equalled during the siege of Berlin, pulverized Finnish lines on the Karelian Isthmus, next door to Leningrad. Next came wave after wave of Soviet assault troops. These were not the shambolic, nearly leaderless hordes of 1939; these were crack troops, well-led, battle-hardened, excellently equipped, and thoroughly trained in replicas of Finnish defensive lines. Finnish high command had not taken seriously the plentiful intelligence and the attack came as a surprise. Taken off guard and shocked by the ferocity of the bombardment, Finnish forces held for a day but were then thrown back in disarray.
On 20th June, Viipuri, once the second-largest city in Finland, fell to the advancing Soviet juggernaut. The next day, Soviet foreign ministry issued peace terms for Finland: an unconditional surrender and occupation in all but name. STAVKA, the Soviet high command, issued new orders for its divisions: break out from the narrow Isthmus and prepare to force the river Kymi, the last remaining natural line of defense before Helsinki.
But by this time, Finnish resistance had begun to stiffen. Stocks of German handheld anti-tank weapons, panzerschreks and panzerfausts, were hurriedly distributed to troops that hadn't even heard of them a week before - because in its infinite wisdom, the Finnish high command had ordered the very existence of these weapons to be kept secret. To secure additional supplies and the services of a German division and a Luftwaffe detachment, President of Finland Risto Ryti had to promise the German foreign office that he would never sign a separate peace with the Soviets.
On the morning of 25th, approximately 150 000 Soviet troops crashed into 50 000 or so Finnish and German defenders in and around the ruins of two small villages, Tali and Ihantala. For three bright days and nightless sub-Arctic nights, the largest battle ever fought in the Nordic countries raged as the irresistible force finally met an immovable object. My grandfather, by then 22 years old but a veteran already, was there; the only thing he ever told me, almost seven decades later, was that nothing he ever heard could even begin to compare with the noise at Ihantala.
Both sides fought with great skill and grim determination, but for one side only the outcome was a matter of life and death. Finnish lines bent, but did not break, and in the end it was the Soviet assault force that was bled white. Smaller attempts elsewhere in the Isthmus were also beaten back, and the lines stabilized. The final attempt was launched on July 26th in the boreal wilderness north of Lake Ladoga, but here, the Finns actually managed to entrap the entire attacking force of two Soviet divisions, capturing all of their heavy equipment.
Soviets were not in a habit of reinforcing failures, certainly not when the race to Berlin was on. On the 22nd, the Soviets had unleashed operation Bagration against German Army Group Center. Reserves were needed to exploit success elsewhere, as conquering Finland would not help the Red Army reach Berlin.
Even though Stalin's plans had been frustrated yet again, he was happy to knock Finland out from the war. A ceasefire was signed on 4th September, followed by a preliminary peace treaty on the 19th. Risto Ryti had kept his promise to the Germans; he just hadn't mentioned that he was no dictator, and once the Soviet assault had been stopped, he promptly resigned his presidency.
The new terms were still harsh, but avoided surrender and occupation. Besides losing everything lost in the Peace of Moscow and some more, the Finnish army had to kick its erstwhile allies, the Germans, from Lapland. Finally, and most importantly, Finland had to pay war reparations to the tune of 300 million pre-war dollars; per capita, an indemnity significantly larger than that demanded in 1919 from Germany.
Acquiring these reparations, which were to be paid in finished goods and equipment, now became a priority for the Soviets. Finnish Communists, who were now free to enter politics after a decade underground, were explicitly forbidden from any actions or provocations that could imperil the reparations deliveries in the slightest.
Meanwhile, Finnish military had began the process of demobilization. Deeply suspicious of Soviet intentions, the military and selected volunteers began to build hidden weapons caches around Finland. Originally planned for a 8000-man nucleus of a resistance force, the enthusiasm for the plan was such that enough weapons, food and equipment for some 35 000 men were stored. In addition, many demobilizing soldiers built their private caches "just in case;" one old soldier kept his squad's weapons hidden but operational until 1994.
This "Weapons Cache Case" could not remain secret for long, but for the Soviets, it was another sign that attempts to occupy Finland or foment a Communist revolution might not go smoothly. Some high-ranking Finnish Communists, including some quite friendly with Stalin, made later sworn statements that this was what ultimately saved Finland from being pushed to Czechoslovakia's path to communism. Historians aren't quite so sure, but agree that weapons caching was one of those things that demonstrated will to fight, while Finnish policies otherwise were so acceptable to the Soviets that occupation or communist takeover weren't necessary. A very recent and quite well-received study - one I've yet to read however - argues that Stalin tried to take over Finland in 1940, 1944 and 1948 and would've succeeded had he really wanted to do so, but was every time content with achieving his overall strategic goals with less expense.
After the war, this became the cornerstone of Finland's foreign policy: everyone knew the Soviet Union could occupy Finland or overthrow her government in favor of communist puppets, but if the costs and dangers of doing so exceeded the improvement in relations or policies that could be achieved, then the Soviets wouldn't probably risk it. This, in effect, was the core of post-war "Finlandization:" the desire not to antagonize an expansionist superpower next door.
The above is based on a melange of books and articles read over the years, but if you want sources for any particular claim or further readings, just ask.